December 8th, 2013, 07:00 AM
Postfix and prefix dry running
how do you evaluate the following expression for x?
compiler gives x=31
x=++a*b + a--;
printf("a is %d b is %d x is %d\n",a,b,x);
December 8th, 2013, 07:39 AM
That is exactly why you shouldn't have that kind of expression.
Sounds like it does the multiplication before increasin a.
which compiler do you use?
December 8th, 2013, 08:31 AM
I use pelles c, i am just trying to understand how operations work in c. Sometimes exams i get questions like this, i want to know the method to solve them.
Originally Posted by MrFujin
December 8th, 2013, 09:19 AM
Learn about sequence points, and the rule that every object can only be modified ONCE between sequence points.
> Sometimes exams i get questions like this
Unless one of the answers is "undefined behaviour", the examiner is just as clueless.
> I use pelles c
It doesn't matter which compiler you use.
Same code with many compilers
If the code has undefined behaviour, then all bets are off.
You get whatever the compiler writer decided should be the result of such nonsense.
December 8th, 2013, 11:48 AM
Thanx for the link, yea examiners are absurd at times
December 8th, 2013, 12:59 PM
In Java class we were shown a similar expression and the instructor was bewildered why he got the answer that he did since it was different from what C would give him. I tried it in several different C-like languages and I examined the assembly code that C generates along with demonstrating how a compiler which evaluated expressions on a stack (such as the Java virtual machine does). I emailed my report to my instructor.
I've posted a copy of that report: Evaluating (x + x * ++x).
The bottom line is that while we have our left-to-right evaluation rules, what really matters is the code that the compiler generates. In Java, which uses a stack to evaluate expressions, the value of the variable when it's encountered going left to right is preserved, whereas in a language that just uses memory, each use of a variable accesses the value from its memory location which could have been changed "unexpectedly" by a later part of the expression.
Also review the concept of sequence points.
And whenever an instructor or examiner presents such a problem without the intent of teaching that you must avoid such expressions, object to such problems and questions citing what you have learned here.
Last edited by dwise1_aol; December 8th, 2013 at 01:26 PM.