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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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 1 (Arithmetic Operators)
- Operators in C | Set 2 (Relational and Logical Operators)
- Why does sizeof(x++) not increment x in C?
- Can we use function on left side of an expression in C and C++?
- Lambda expression in C++
- std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
- What are the operators that can be and cannot be overloaded in C++?
- Order of operands for logical operators
- Advanced C++ | Conversion Operators
- const_cast in C++ | Type Casting operators
- Bitwise Operators in C/C++
- How to sum two integers without using arithmetic operators in C/C++?
- Execution of printf with ++ operators
- Conditionally assign a value without using conditional and arithmetic operators
- new and delete operators in C++ for dynamic memory