Bug 17253

Summary: Inconsistency in reading array indexes
Product: gcc Reporter: Jasper van Veghel <vanveghel>
Component: cAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: normal CC: gcc-bugs
Priority: P2    
Version: 3.3.4   
Target Milestone: ---   
Host: 3.3.4 Target: 3.3.4
Build: 3.3.4 Known to work:
Known to fail: Last reconfirmed:

Description Jasper van Veghel 2004-08-31 19:50:44 UTC
Consider the following two snippets:

-- snip snip --

#include <stdio.h>
#include <string.h>

int main (void) {
        char test[5][5];
        int j = 3;

        memset (&test, ' ', 5 * 5);

        test[j][j++] = '!';

        printf ("test[3][3] = %c\ntest[4][3] = %c\n",
                test[3][3], test[4][3]);

        return 0;
}

-- snip snip --

And:

-- snip snip --

#include <stdio.h>
#include <string.h>

int main (void) {
        char test[5][5];
        int j = 3;

        memset (&test, ' ', 5 * 5);

        test[(j == 4) ? 4 : 3][j++] = '!';

        printf ("test[3][3] = %c\ntest[4][3] = %c\n",
                test[3][3], test[4][3]);

        return 0;
}

-- snip snip --

Running both these snippets produces the following results with GCC 3.3.4
running on Debian GNU/Linux Unstable (x86):

$ ./test
test[3][3] =
test[4][3] = !
$ ./test2
test[3][3] = !
test[4][3] =
$

It seems that j++ is evaluated first only in the second case, making the
statement in the first bracket evaluate to 4.
This may be a result of 'undefined behavior' caused by sequence points, and
indeed, GCC does issue a warning ("warning: operation on `j' may be undefined"),
but it does seem like something that can at least be improved.

Kind Regards,

Jasper
Comment 1 Falk Hueffner 2004-08-31 20:03:36 UTC
Uhm, the code is invalid, and the compiler warns about it. What could possibly
be improved?
Comment 2 Andrew Pinski 2004-08-31 20:44:31 UTC
No there is nothing which can be improved except maybe for you fixing your code not be use undefined  
code.
Comment 3 Wolfgang Bangerth 2004-08-31 20:46:05 UTC
Indeed. What more than a warning do you want?  
Comment 4 Wolfgang Bangerth 2004-08-31 20:46:29 UTC
Duplicate of PR 11751. 

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