-2

Cannot explain the output of the following program. According to my knowledge the output should be 19, but running it gives me output of 20. I used gcc to compile this program.

int main()
{ 

    int x, y = 5;

    x = ++y + ++y + --y;
    printf("%d", x);

    return 0;
}
fuz
  • 88,405
  • 25
  • 200
  • 352
Aakash Sigdel
  • 9,060
  • 5
  • 33
  • 38

2 Answers2

2

Your program exploits undefined behavior as you modify y multiple times between two sequence points (in your case, the end of the statement). If you turn on warnings with -Wall, your compiler is probably even going to warn you about that.

fuz
  • 88,405
  • 25
  • 200
  • 352
-6

6+7+6 = 19 so 19 will be your output

Faisal Amjad
  • 107
  • 2
  • 4
  • 10
  • 1
    No. This is undefined behavior. Your compiler might return whatever it wants. – fuz Feb 23 '13 at 16:54
  • I suggest you test it out. My machine also gives 20 as stated in the question, but it's undefined behavior so the compiler would be within its rights to print a million or delete your hard drive. – Kevin Feb 23 '13 at 16:56
  • @Kevin: What happened to nasal daemons? – thejh Feb 23 '13 at 17:01
  • @thejh Sure, those too, but I can't list all the calamities that could befall a user of undefined behavior :) – Kevin Feb 23 '13 at 18:08