The order of operands of logical operators &&, || are important in C/C++.
In mathematics, logical AND, OR, etc… operations are commutative. The result will not change even if we swap RHS and LHS of the operator.
In C/C++ (may be in other languages as well) even though these operators are commutative, their order is critical. For example see the following code,
The first part pTemp will be evaluated against NULL and followed by pTemp->Next. If pTemp->Next is placed first, the pointer pTemp will be dereferenced and there will be runtime error when pTemp is NULL.
It is mandatory to follow the order. Infact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of AND (&&) expression is guaranteed to be 0.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- sizeof operator in C
- Bitwise Operators in C/C++
- Difference between ++*p, *p++ and *++p
- To find sum of two numbers without using any operator
- Sequence Points in C | Set 1
- A comma operator question
- Result of comma operator as l-value in C and C++
- Function overloading and return type
- Structure Member Alignment, Padding and Data Packing
- Increment (Decrement) operators require L-value Expression
- Precedence of postfix ++ and prefix ++ in C/C++
- Modulus on Negative Numbers
- C/C++ Ternary Operator - Some Interesting Observations
- Evaluation order of operands
- Operands for sizeof operator