Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22197

Apparently undocumented GCC behaviour with "constant" initializers in C

$
0
0

Consider the following C code:

#include <stdio.h>int x = 5;int y = x-x+10;int z = x*0+5;int main(){  printf("%d\n", y);  printf("%d\n", z);  return 0;}

The ANSI C90 standard states "All the expressions for an object that has static storage duration [...] shall be constant expressions" (6.5.7 constraint 3).

Clearly the initializers for y and z are not constant expressions. And indeed, trying to compile the above C code with clang main.c or clang -ansi main.c gives an error for this reason.

However, compiling with gcc main.c or even gcc main.c -ansi -pedantic -Wextra -Wall gives no errors at all, and runs, printing 10 and 5.

On the other hand, trying something like the following:

#include <stdio.h>int x = 5;int main(){  int y[x-x+2];  printf("%lu\n", sizeof(y));  return 0;}

gives a warning when compiled with gcc -ansi -pedantic ... or clang -ansi -pedantic ....

So gcc randomly performs the mathematically correct cancellations in order to pretend that something is a constant expression, even when asked not to (-ansi). Why is this? Is this a bug?

By the way, my gcc version is 9.4.0 and my clang version is 10.0.0-4.


Viewing all articles
Browse latest Browse all 22197

Trending Articles