Bug 39143

Summary: Incorrect compilation involving assignment by addition/substraction
Product: gcc Reporter: Eduardo Robles Elvira <edulix>
Component: cAssignee: Not yet assigned to anyone <unassigned>
Severity: normal CC: alduc1, alexey, algorithmus, asokumar, astier, av1474, bala, barnarr, behloul.younes, bmead15, buergel, calliari, carpman, chuchunxin, devnull, d_picco, edulix, eric.mcvicker, fuchsia.groan, gaurav_har, gcc-bugs, gcc, ggs, gjasny, j.witteveen, jandres, janis, jesser, jompo, krs, lid, lindahlb, lxg8906, mayer, mikaldaz, mike.clarkson, nakkore, nanericwang, nobs, pierre.van.de.laar_at_philips.com, qyang, ramiller, raoulgough, raphael.ribas, rglan, rjvbertin, robc, s9322036, SimonX200, smartmouse714, super.aorta, svetozarmarkov, tczarnecki, terrix, tim.bruylants, vanveghel, vitaly, windows2000d, zshao
Priority: P3    
Version: 4.2.4   
Target Milestone: ---   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed:

Description Eduardo Robles Elvira 2009-02-09 18:41:51 UTC
A friend of mine have noticed an error in GCC when he was developing his own C compiler. The problem happens when using -O0 (no optimization) and local vars. See sample code:

#include <stdio.h>

int jj = 0, ii = 0; //global vars

int main()
    int j = 0, i = 0; // local vars

    i -= i += 2; // i = 0 is correct
    ii -= ii += 2; // ii = -2 => incorrect, should be 0 too

    printf("i: %d ii: %d\n", i, ii);
    return 0;

The output is:
$ gcc main.c -o main -O0 && ./main
i: 0 ii: -2

As you can see, the same code (using code "var -= var += value;") returns a different value depending if the var is local or global. Also note that, oddly enough, when we use optimizations then the compilated code turns correct in both cases:

$ gcc main.c -o main -O1 && ./main
i: 0 ii: 0

Same happens when using C++. This is the gcc version:
$ gcc -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --enable-languages=c,c++,fortran,objc,obj-c++,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.2 --program-suffix=-4.2 --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-mpfr --enable-targets=all --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu
Thread model: posix
gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu3)
Comment 1 Andrew Pinski 2009-02-09 18:45:28 UTC
This code is undefined as you are assigning to the variable i without a sequence point inbetween the assignment.

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