If a=2 then a++ + ++a == 42. How?
Anurag Rana
Posted on June 25, 2019
Any C programming exam having objective questions, be it class test or campus placement exam, I am sure you must have faced these type of question more than once.
Yes….I know…. I can understand….
Few people never understand the logic behind this and they keep asking such questions again and again and again…..
if a=2, then what will be the value of ++a + a++ + a++?
some geniuses even go beyond this and they will make a long statement which will not even fit in one line of an A4 sheet.
a = a++ + ++a + a++ + a++ + ++a ….. and so on….
Rule is if a=2 then a++ + ++a could be equal to 2, it could be equal to 4, 5, 42, 99 and even 2048. Basically in such situations compiler can output anything it wants.
What is the Rule:
As some of you might as well know that the answer to questions like above is ‘compiler dependent’ or is ‘unpredictable’. Right.
How?
So there is something known as ‘Sequence point’ in C. After each and every sequence point compiler evaluates whatever it has encountered so far after the previous sequence point.
So a semicolon (; ASCII 59) is the sequence point in C. Compiler evaluates everything when it encounters the semicolon before moving to the next statement.
If there is something like
int numberOne = 2, numberTwo=3;
sum = numberOne + numberTwo;
printf(“%d”, sum);
the sum will be printed as 5 because the compiler will evaluate sum in the second statement before moving to printf statement.
But how compiler evaluates things within a sequence point comes with NO guarantee. in a statement like
i = j++ + k++;
one can’t guarantee whether j will be incremented first or k will be incremented first. Although it doesn’t even matter in some case which one will be evaluated first. But in some cases, it may reduce a CSE student’s package from 10 LPA to 6 LPA.
What about undefined behavior:
C standards say that the value of a variable can change at most once inside a single sequence point. But in statements like a++ + ++a we change values of a more than once. This is not allowed as per C compiler. You break the rule, Compiler does the same.
So basically if you ever face this type of question in future then the most suitable answer is
— Unpredictable or compiler dependent
If no such option is given, talk to the teacher and politely direct him towards this blog.
More from the Author:
- How to host the django app on pythonanywhere for free
- Top 5 Python Books
- Programming on Raspberry Pi with Python: Controlling LED
- Programming On Raspberry Pi With Python: Activate LED and Buzzer on Motion Detection
- Programming on Raspberry Pi with Python: Sending IP address on Telegram channel on Raspberry Pi reboot
- Sending Emails Using Python and Gmail
Posted on June 25, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.