Thursday, July 9, 2009

C++ programming?

Given the line:


a += ++a + a++;





What is the correct translation of the given code line?





a) a = a + a;


a = a + 1;


a = a + a;





b) a = a + 1;


a = a + a + a;


a = a + 1;





c) a = a + 1 + 1;


a = a + a + a;





d) a = a;


a = a + 1;


a = a + 1;


a = a;

C++ programming?
the answer is B





first the pre-increment (++a) is applied which can also be written


a=a+1





then the expression is evaluated as


a += a+a


which can be written


a = a + a + a





lastly, the post-increment is performed, which can be written


a = a + 1





Just remember that ++ or -- before the variable is pre, and is evaluated before the expression. ++ or -- after the variable means it is a post, and is evaluated after the expression. Also, a particular variable can only have one value at a time, so it will never have different values in the same expression.


For example: say x=1...


x = ++x + x


will be


x = 2 + 2


and NOT


x = 2 + 1
Reply:The real answer is "none of the above, or possibly any of the above". Do a Google search for "sequence points", and you'll find that that code does not have a well--defined meaning in standard C or C++.





That probably won't get you any points on your homework, but perhaps your instructor will learn something :-)


No comments:

Post a Comment