2081 8

BIT102 ยท 2081 ยท 5 marks

What is operator precedence? Explain assignment and logical operator. [1+4]

What is operator precedence? Explain assignment and logical operator. [1+4]

C ProgrammingChapter 3: Operators and ExpressionsOperator precedence and associativity

Quick answer

Operator precedence defines the order (priority) in which operators are evaluated in an expression when multiple operators appear together. An operator with higher precedence is evaluated before an operator with lower precedence.

Operator Precedence, Assignment and Logical Operators


Operator Precedence [1 mark]

Example:

2 + 3 * 4  =  2 + 12  =  14

Here, * has higher precedence than +, so multiplication is performed first.


Assignment Operator [2 marks]

The assignment operator is used to assign a value to a variable. The basic assignment operator is =.

Syntax:

variable = expression;

Simple Assignment

OperatorExampleMeaning
=a = 5Assigns 5 to a

Compound Assignment Operators

These combine an arithmetic operation with assignment:

OperatorExampleEquivalent To
+=a += 5a = a + 5
-=a -= 5a = a - 5
*=a *= 5a = a * 5
/=a /= 5a = a / 5
%=a %= 5a = a % 5

Key Points:

  • Assignment is right-to-left associative
  • Multiple assignments are possible: a = b = c = 10; (assigns 10 to all)
  • The right-hand side is evaluated first, then assigned to the left-hand side variable

Logical Operators [2 marks]

Logical operators are used to combine or negate boolean/conditional expressions. They return either true (1) or false (0).

Types of Logical Operators

OperatorNameExampleResult
&&Logical ANDa && bTrue only if both a and b are true
||Logical ORa || bTrue if at least one of a or b is true
!Logical NOT!aTrue if a is false, and vice versa

Truth Tables

AND (&&)

ABA && B
000
010
100
111

OR (||)

ABA || B
000
011
101
111

NOT (!)

A!A
01
10

Example in C:

int a = 5, b = 10, c = 0;

if (a > 0 && b > 0)       // true && true = true
    printf("Both positive");

if (a > 0 || c > 0)       // true || false = true
    printf("At least one positive");

if (!c)                    // !0 = true
    printf("c is zero");

Key Points:

  • && and || use short-circuit evaluation: if the result is determined from the first operand, the second is not evaluated
  • ! is a unary operator (operates on one operand)
  • Logical operators are commonly used in if, while, and for conditions

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.