Facebook

If a=2 then a++ + ++a == 42. How?


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 Indian teachers never understand the law 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 self-proclaimed geniuses even goes beyond this and they will make a long statement which will not even fit in one line of 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. Don't be surprise if compiler output something like this..


basically in such situations compiler can output anything it want.

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 encounter 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);

sum will be printed as 5 because compiler will evaluate sum in second statement before moving to printf statement.

But how compiler evaluate 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 behaviour :

C standards says that value of a variable can change at most once inside a single sequence point. But in statements like a++ + ++a we changes values of a more than once. This is not allowed as per C compiler. You break the rule, Compiler do the same.

So basically if you ever face this type of question in future then 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.

Good Luck.



No comments:

Post a Comment