Two different outputs

#include<stdio.h> int main(void) { static int i=i++, j=j++, k=k++; printf("i = %dj = %dk = %d", i, j, k); return 0; } 

Exit to Turbo C 4.5:

i = 0 j = 0 k = 0

In gcc, I get an error:

The initializer element is not a constant

Which one is logically correct? I'm confused.

+4
source share
5 answers

The standard says about initialization (6.7.8):

4 & emsp; All expressions in the initializer for an object with a duration of static storage must be constant expressions or string literals.

(This is from C99, but C89 says pretty much the same thing.)

Thus, it seems that GCC is more correct than 15-year-old fault tolerance. (Who would say that?)

+12
source

I know this is not an answer, but still, why use a complex test example?

Ok, simplify everything:

 #include<stdio.h> int main(void) { static int i; printf("i = %d", i); return 0; } 

Conclusion:

 i = 0 

But what if ...?

  #include<stdio.h> int main(void) { static int i=i; printf("i = %d", i); return 0; } 

Conclusion:

 prog.c: In function 'main': prog.c:4: error: initializer element is not constant 
+2
source

GCC is true here.

static variables are initialized (at boot time) to the value specified in the initializer (or to 0 if no initializer is specified). Since this initialization occurs before the program starts, initializers for static variables must be compile-time constants. An expression containing a ++ operator is clearly not a constant expression.

+1
source

I would suggest that the GCC is true here. The initializer must not be a variable. You are trying to initialize a variable with itself before it is defined.

I assume that Turbo C has β€œreasons” that i is the entire static variable and therefore should have a value of 0 (like all static variables by default), then it continues to ignore the ++ operation.

0
source

buddy u havent initialized the variables and ur incremented them, since u did not initialize any variable, it will take on a value for garbage, and I do not think that increasing the amount of garbage is the right thing. Therefore, first initialize the variables, and then increase them. U will get the correct answer.

0
source

All Articles