Bug 3165

Summary: ANSI C standard violation
Product: gcc Reporter: tczarnecki
Component: cAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: enhancement CC: gcc-bugs, jsm28
Priority: P3    
Version: unknown   
Target Milestone: ---   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed:

Description tczarnecki 2001-06-13 05:36:01 UTC
The order of expression evaluation is bad. The example code produces output like that:

1, a=1, b=1, c=1
2, a=1, b=1, c=1
3, a=1, b=1, c=1
11, a=3, b=2, c=1
1, a=1, b=1, c=1
2, a=1, b=1, c=1
3, a=1, b=1, c=1
22, a=2, b=1, c=1
1, a=1, b=1, c=1
2, a=1, b=1, c=1
3, a=1, b=1, c=1
33, a=1, b=1, c=1

But it should look like:

3, a=1, b=1, c=1
2, a=1, b=1, c=1
1, a=1, b=2, c=1
11, a=3, b=2, c=1
2, a=1, b=1, c=1
3, a=1, b=1, c=1
1, a=1, b=1, c=1
22, a=2, b=1, c=1
3, a=1, b=1, c=1
2, a=1, b=1, c=1
1, a=1, b=1, c=1
33, a=1, b=1, c=1

It looks like exressions are evaluated first and then operators are applied. But I don't think it should work that way. Microsoft VC 6.0 compiler has some problems too  but only += like operators case an error. In this case output looks like:

1, a=1, b=1, c=1
2, a=1, b=1, c=1
3, a=1, b=1, c=1
11, a=3, b=2, c=1
2, a=1, b=1, c=1
3, a=1, b=1, c=1
1, a=1, b=1, c=1
22, a=2, b=1, c=1
3, a=1, b=1, c=1
2, a=1, b=1, c=1
1, a=1, b=1, c=1
33, a=1, b=1, c=1

Release:
unknown

Environment:
Sun Solaris 2.6 (Sparc)

How-To-Repeat:
/*Compile this file with no options*/
#include <stdio.h>

foo(int n, int a, int b, int c)
{
  printf("%d, a=%d, b=%d, c=%d\n", n, a, b, c);
}

int main()
{
  int a=1, b=1, c=1;
  *(foo(1, a, b, c), &a) += *(foo(2, a, b, c), &b) += *(foo(3, a, b, c), &c);
  foo(11, a, b, c);
  a=1, b=1, c=1;
  *(foo(1, a, b, c), &a) = *(foo(2, a, b, c), &b) + *(foo(3, a, b, c), &c);
  foo(22, a, b, c);
  a=1, b=1, c=1;
  *(foo(1, a, b, c), &a) = *(foo(2, a, b, c), &b) = *(foo(3, a, b, c), &c);
  foo(33, a, b, c);
  return 0;
}
Comment 1 Joseph S. Myers 2001-06-13 06:19:09 UTC
State-Changed-From-To: open->closed
State-Changed-Why: Not a bug.  Re-read the C standard, in particular the rules
    on sequence points.  Your program has undefined behavior.
Comment 2 Andrew Pinski 2005-04-20 02:41:55 UTC
Reopening to ...
Comment 3 Andrew Pinski 2005-04-20 02:42:14 UTC
Mark as a dup of bug 11751.

*** This bug has been marked as a duplicate of 11751 ***