What will be the output of the following program?
A) 11 B) 10 C) -9 D) None
Answer: D, None – Compilation Error.
In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Providing an R-value or a const qualified variable results in compilation error.
In the above program, the expression -i results in R-value which is operand of pre-increment operator. The pre-increment operator requires an L-value as operand, hence the compiler throws an error.
The increment/decrement operators needs to update the operand after the sequence point, so they need an L-value. The unary operators such as -, +, won’t need L-value as operand. The expression -(++i) is valid.
In C++ the rules are little complicated because of references. We can apply these pre/post increment (decrement) operators on references variables that are not qualified by const. References can also be returned from functions.
Puzzle phrased by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- lvalue and rvalue in C language
- Execution of printf with ++ operators
- Operators in C | Set 1 (Arithmetic Operators)
- sizeof operator in 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++
- Order of operands for logical operators
- Precedence of postfix ++ and prefix ++ in C/C++
- Modulus on Negative Numbers
- C/C++ Ternary Operator - Some Interesting Observations
- Pre-increment (or pre-decrement) in C++
- Operands for sizeof operator