Discussion
What value will be stored in z if the following code is executed?
main()
{
int x = 5, y = -10, z;
int a = 4, b = 2;
z = x+++++y * b/a;
}
Answer: C
Correct answer: Compilation error
The expression z = x+++++y * b/a; does not compile, and the reason is the rule the C standard uses to split a line into tokens - the maximal munch rule. The scanner takes the longest sequence of characters that could form a valid token at each step, and it does so without looking ahead to see whether the result will parse. Faced with +++++, it therefore produces ++, then ++, then +, giving ((x++) ++) + y. That is where it fails: x++ is an rvalue - a value, not an object - and the increment operator requires a modifiable lvalue as its operand. GCC reports lvalue required as increment operand. The fix a programmer would apply is whitespace, since the scanner respects it: written as x++ + ++y * b/a the expression is legal, and it evaluates to \[ 5 + \frac{(-9) \times 2}{4} = 5 + \frac{-18}{4} = 5 + (-4) = 1, \] because integer division in C truncates towards zero. So even under the grouping the question intends, the value is 1 rather than the 2 this record originally offered; as written, the code never gets that far. The declaration line also carried a stray semicolon, leaving y undeclared, and has been corrected.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development