I have the following code and I expect the output is:
foo(0) -- 2 /* 1*2 */
foo(2) -- 12 /* 3*4 */
foo(4) -- 30 /* 5*6 */
but I've got
foo(2) -- 4
foo(4) -- 16
foo(6) -- 36
instead. Can someone explain to me what happened?
include <stdio.h>
int main()
{
int counter; /* counter for loop */
counter = 0;
while (counter < 5)
printf("foo(%d) -- %d\n", counter, ((++counter)*(++counter)));
return (0);
}
Once you've used ++
-- prefix or postfix -- on a variable, you can't use it again on the same variable until after the next sequence point. If you do, the behavior of the code is undefined -- the compiler is allowed to do anything it wants.
There are no sequence points between the two (++counter)
expressions in your code, so you've run afoul of this rule. You have to write something like this, instead:
while (counter < 5) {
printf("foo(%d) -- %d\n", counter, (counter+1) * (counter+2));
counter += 2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With