Optimization of variables

Axel Freyn axel-freyn@gmx.de
Wed Feb 3 18:42:00 GMT 2010

Hi Marcus,
> Will the following C code :
> int y;
> {
>    int   x1, x2;
>    x1 = 3;
>    x2 = 4;
>    y = x1 + x2;
> }
> be compiled as :
> int y = 7;
> automatically, without creating the extra variables on the stack and  
> performing the addition calculation?
Well, my version of gcc does not compile your code - it claims:
test.c:2: error: expected identifier or ‘(’ before ‘{’ token
Wenn I try 
int main(){
  int y;
it works.
> Is this true of all code, or only with certain optimizations (e.g. -O2).
It depends on the optimiziations. For my machine and my
compiler-version, without -O gcc is performing the complete
calculations. However, with -O or higher, it is directly using "y=7".
In general, I think you can say almost nothing about the precise
behaviour of the optimizer (at least: I can't - maybe some of the
gcc-developers can..) 
There is a quite "easy" way to check your questions:
Create 2 files:
int main()
 int y;
 int   x1, x2;
 x1 = 3;
 x2 = 4;
 y = x1 + x2;

and test2.c:
int main()
 int y = 7;
Now, if you compile both into assembler-code (using gcc -S), both
resulting files are different (and "test1.s" contains even the number
3). However, when adding -O, they become identically. 

But the big problem in this test is: gcc seems to detect that "y" is
never used - the file
int main(){}
which does nothing produces exactly the same assembler code...

So in order to be sure, you probably have to use a more elaborate
example, e.g. add a printf("%d",y) at the end of main. 



More information about the Gcc-help mailing list