Optimization problem with local array initializers

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I have a strange problem which shows up with -O1, but does not apepar
with -O0. I would otherwise report as a bug, but it appears to be present
in several gcc versions dating back to at least 2.95 and including 3.4.0.
I find it hard to believe that such a bug would persist that long, so I think
it is more likely that I have overlooked something myself. The code is
simple:

-----------------------------------------------------------
#include <stdio.h>

const unsigned table[2]={1,0};

int main(int argc,char **argv)
{
	unsigned a=0;

	const unsigned b[1]={ a };
	a=table[b[0]];

	printf("%u\n",b[0]);
	return 0;
	}
-----------------------------------------------------------

In my mind, b[0] should get initialized as 0, and after that "a" should
be set to table[0], which is 1. With -O0, that indeed happens.
But with -O1, there is some confusion about the order of b[] initialization
and the subsequent a=table[b[0]] statement, and in the process,
b[0] gets the value 1:

# gcc -pedantic -O1 -o bug bug.c ; echo -n 'with optimize: ' ; ./bug
bug.c: In function `main':
bug.c:9: warning: initializer element is not computable at load time
with optimize: 1

# gcc -O0 -o bug bug.c ; echo -n 'without optimize: ' ; ./bug
without optimize: 0

# gcc -v
Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/3.3.3/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --disable-libunwind-exceptions --with-system-zlib --enable-__cxa_atexit --host=i386-redhat-linux
Thread model: posix
gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7)

What is going on? I suspected some strange rule about sequence points
or aliasing rules, but I can't find anything like that in the standard
documents.

As you can see, I get a warning with -pedantic. But what does the
warning mean? Sure, the initializer is not known at load time, but
AFAIK that does not constitute any standard violation. Also, with
more complex code I have seen the same counter-intuitive results,
but without the warning.

Ahti Heinla

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux