-3

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

Please explain the reason for the following outputs.

#include <stdio.h>

int main()
{
    int i = 0, j = 0;
    int val1 = 0;
    int val2 = 0;

    val1 = i+++i+++i++ ;
    val2 = ++j+++j+++j ;

    printf("value = %d\n", val1);
    printf("value = %d\n", val2);
    return 0;
}

Output :

value = 0  
value = 7
Community
  • 1
  • 1
Navaneeth Sen
  • 6,315
  • 11
  • 53
  • 82

2 Answers2

1

Multiple changes of variables without an intervening sequence point is undefined behaviour.

This means that there is no definition in the specification for what should happen. The compiler is allowed freely to do whatever it wants -- anything at all.

Sequence points are only present at ;, &&, ||, ? and : in the ternary operator, and , (the comma operator, not to be confused with the comma separating arguments in a function call).

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
  • hey, but i got it compiled successfully in my ubuntu 11.04 PC. and it executed without any errors. – Navaneeth Sen Apr 13 '12 at 11:25
  • 2
    Undefined behaviour doesn't necessarily have to result in an error, or failure to compile. It could compile, and theoretically do anything at all, according to the ISO C specification. – Delan Azabani Apr 13 '12 at 11:26
  • Yes, it works, but the results aren't guaranteed to be the same on other versions or platforms, even when using other compilers adhering to the standard, too (because this is outside the standard). If you'd like to compare it, it's like taking a power line and coming to the conclusion that there's always the left wire being hot. – Mario Apr 13 '12 at 11:28
  • @Sen: the issue is that the order in which expressions are evaluated and side effects are applied is *unspecified*; the compiler is free to evaluate those expression in any order it wants. Because of this, the result will vary from compiler to compiler (or even with the same compiler with different optimization settings). The language standard leaves the behavior *undefined* so the compiler isn't obligated to detect those cases and issue a diagnostic. As far as the language definition is concerned, *any* result is "correct". – John Bode Apr 13 '12 at 11:31
1

You are modifying the same variable more than once without an intervening sequence point, this is Undefined Behavior.
An Undefined behavior simply means that there may or may not be any feasible explanation to the behavior of the program.

Good Read:
Undefined behavior and sequence points

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533