0

Possible Duplicate:
Undefined Behavior and Sequence Points

Working out the below code by hand:

#include <stdio.h>

int func (int a, int b) {
    static int c = 1;
    return a + b * (c *= -1);
}

int main () {
    int a = 2, b = 3;
    int c = func(a, b);

    a *= a++;
    b *= ++b;

    printf("%d %d %d %d\n", a, b, c, func(a, b));
}

I calculate the variables in printf() to be as follows:

a = 5, b = 16, c = -1, func(a, b) = -11

however my compiler tells me the last value is in fact 21.

Output:

a = 5, b = 16, c = -1, func(a, b) = 21n

I'd calculate my value as (16*-1) + 5

Can anyone tell me where I have gone wrong?

Community
  • 1
  • 1
Gga
  • 4,311
  • 14
  • 39
  • 74

1 Answers1

4
a *= a++;
b *= ++b;

both statements are undefined behavior in C. They are violating C sequence points rules.

a *= a++; 

is equivalent to:

a = a * a++;

and modifying an object twice between the previous and the next sequence point is undefined behavior in C (C99, 6.5p2).

ouah
  • 142,963
  • 15
  • 272
  • 331
  • @RodgersandHammertime neither – ouah Oct 26 '12 at 11:56
  • So please explain to me what's happening and why my first 3 answers are correct? – Gga Oct 26 '12 at 11:58
  • How does b get to 16 is what I'm asking? – Gga Oct 26 '12 at 11:59
  • `How does b get to 16` as it is undefined behavior, the compiler is free to set this value to 16, 42 or whatever. – ouah Oct 26 '12 at 12:00
  • That's ridiculous, how could this be an exam question then with no clear answer? please clarify. – Gga Oct 26 '12 at 12:02
  • Not to say I don't believe you, am just curious as to why such a thing could happen? – Gga Oct 26 '12 at 12:03
  • The answer is: this program is erroneous. Don't expect any reliable output from it. It is the same way this is erroneous: `printf("%d\n", 1 / 0);` is. – ouah Oct 26 '12 at 12:04
  • Yes, but there is a documented answer to this question and it is from a reputable exam board. How, if the compiler has done what it likes with b, have I calculated the same answer for B? – Gga Oct 26 '12 at 12:06
  • Well, it seems that the exam board in question is only "reputable"... – Ivan Vergiliev Oct 26 '12 at 12:08
  • @IvanVergiliev That's a bit like saying, "this person is only 'trusted'" – Gga Oct 26 '12 at 12:12
  • Anyway thanks @ouah for you help, I will explore some more :) – Gga Oct 26 '12 at 12:13
  • @RodgersandHammertime trust me this program is wrong, and the only correct answer is: the behavior is undefined. – ouah Oct 26 '12 at 12:13