-2

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

int main()
{
int a=1;
printf("%d %d %d",a,a++,++a);
return 0;
}

The above code is giving output 3 2 3 why????

Community
  • 1
  • 1
Tushar Mishra
  • 177
  • 1
  • 7
  • 3
    Hmmmm, I wonder what teacher is giving out this silly homework (http://stackoverflow.com/questions/14120417/what-is-the-order-of-calling-convention-in-c-and-c). – R. Martinho Fernandes Jan 02 '13 at 11:05

3 Answers3

3

It actually undefined in c and c++.

Undefined : modifying a scalar value twice between sequence points, which is what your code is doing. f(i++, ++i) is undefined behaviour because it modifies i twice without an intervening sequence point.

A good list of definitions

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
2

This is undefined behaviour

a++, ++a is done in same sequence point and this is undefined behaviour.

From Undefined behavior and sequence points :

In the Standard in §5/4 says

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

What does it mean?

Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

The mechanics of pre- and postincrementing are described here : http://c-faq.com/expr/evalorder2.html . However, this expression is undefined as mentioned in the previous answers.

Danstahr
  • 4,190
  • 22
  • 38