-4

Possible Duplicate:
Undefined Behavior and Sequence Points
pre fix and post fix increment in C

Please explain how this program goes on to print i=2

#include<stdio.h>
void main()
{
    int i=1;
    i=i+2*i--;
    printf("%d",i);
}

By the logic it should evaluate the value 3 because -- 1+2*1=3 But this first evaluates i-- and the updates the value of i. Why is this happening? :S

Community
  • 1
  • 1
ross
  • 388
  • 2
  • 4
  • 10

3 Answers3

3

Modifying a variable in an expression and then assigning that result to the same variable is undefined behavior, so any behavior you're seeing is technically correct (including rebooting the computer, or destroying the universe). From the C standard, §6.5.2:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.

To fix it, move the post-decrement out of the expression, like this:

int main() {
    int i=1;
    i=i+2*i;
    i--;
    printf("%d",i);
    return 0;
}
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
2

i=i+2*i--;

This code invokes Undefined Behavior. You are modifying i and reading it within a single sequence point. Please read about Sequence Points.

How can I understand complex expressions like the ones in this section, and avoid writing undefined ones? What's a ``sequence point''?

Sadique
  • 22,572
  • 7
  • 65
  • 91
-1
i = i + 2 * i--;
i = 1 + 2 * 1;  (as it is post decrement so the i value is still 1)
i = 1 + 2;   (multiplication has higher priority, post decrement still not made)
i = 3 ;
on the next statement
printf("%d",i); the post decrement is done here on i and i value is 3 so 3 -1 = 2
The output is 2 

pre-decrement or preincrement are made on the same statements whereas post increments and post decrements are made on the next statement . I remember i read it somewhere This is i Have explained to make you clear on pre and post operations

but mostly belive ITS UNDEFINED BEHAVIOR when you try to do increment and decrements operations on the same variable which is to be assigned a value

niko
  • 9,285
  • 27
  • 84
  • 131
  • 1
    The statement "pre-decrement or preincrement are made on the same statements whereas post increments and post decrements are made on the next statement" isn't correct. Exactly when the side effect is applied isn't specified apart from requiring it be applied before the next sequence point. In a well-defined expression like `a = b * c++`, the side effect could be applied to `c` immediately after `c++` is evaluated, or after `b * c++` is evaluated, or after the result of `b * c++` is assigned to `a`. – John Bode Sep 30 '11 at 14:05