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]
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
| Operator | Example | Meaning |
|---|---|---|
= | a = 5 | Assigns 5 to a |
Compound Assignment Operators
These combine an arithmetic operation with assignment:
| Operator | Example | Equivalent To |
|---|---|---|
+= | a += 5 | a = a + 5 |
-= | a -= 5 | a = a - 5 |
*= | a *= 5 | a = a * 5 |
/= | a /= 5 | a = a / 5 |
%= | a %= 5 | a = 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
| Operator | Name | Example | Result |
|---|---|---|---|
&& | Logical AND | a && b | True only if both a and b are true |
|| | Logical OR | a || b | True if at least one of a or b is true |
! | Logical NOT | !a | True if a is false, and vice versa |
Truth Tables
AND (&&)
| A | B | A && B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
OR (||)
| A | B | A || B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
NOT (!)
| A | !A |
|---|---|
| 0 | 1 |
| 1 | 0 |
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, andforconditions
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.