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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Difference between Increment and Decrement Operators
- Pre-increment (or pre-decrement) in C++
- Increment (++) and Decrement (--) operator overloading in C++
- lvalue and rvalue in C language
- Pre-increment and Post-increment in C/C++
- Operators in C | Set 2 (Relational and Logical Operators)
- Operators in C | Set 1 (Arithmetic Operators)
- Why does sizeof(x++) not increment x in C?
- Lambda expression in C++
- Can we use function on left side of an expression in C and C++?
- std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
- # and ## Operators in C
- Operators in C / C++
- unordered_set operators in C++ STL
- C | Operators | Question 2