Self-referring const array initialisation

Hamilton, Ian Ian.Hamilton@gbr.xerox.com
Thu Apr 15 10:04:00 GMT 2004


Hi there

Here is a test program to illustrate a problem in some code
I have inherited:

#include <stdio.h>

const int array1[5]=
{
  1,
  2,
  3,
  4,
  5
};

const int array2[5]=
{
  1,
  array2[0] + 1,
  array2[1] + 1,
  array2[2] + 1,
  array2[3] + 1,
};

int main()
{
  printf ("Array values:\n\n");
  printf("array1  array2\n");

  printf("  %i       %i\n", array1[0], array2[0]);
  printf("  %i       %i\n", array1[1], array2[1]);
  printf("  %i       %i\n", array1[2], array2[2]);
  printf("  %i       %i\n", array1[3], array2[3]);
  printf("  %i       %i\n", array1[4], array2[4]);
}


If I build and run this on a Sun/Sparc/Solaris system using
gcc version 2.95.2, I get the following output:

Array values:

array1  array2
  1       1
  2       2
  3       3
  4       4
  5       5


However, if I use gcc version 3.3.2, I get this output:

Array values:

array1  array2
  1       1
  2       1
  3       1
  4       1
  5       1


A bit of investigation with the debugger revealed that the
initialisation code is producing the initialised array on the
stack, then copying it to its normal position in RAM. Unfortunately,
the initialisation code is reading values from the array's normal
position in RAM, so reads a zero for the array elements already
initialised instead of the initialised value.

My question is whether this sort of self-reference is allowed by
the C and/or C++ standards. In other words, is this a compiler bug,
or a bug in the above code?

Cheers,
Ian.



More information about the Gcc-help mailing list