clinuxdisassembly

How is code working after Optimising?


While studying Compiler optimizations, I simply compiled following piece of code :

#include<stdio.h>
struct fraction {
    int num ;
    int denum ;
};

int main()
{
  struct fraction pi;
  pi.num = 22;
  pi.denum = 7;
  return 0;
}

using

gcc test.c -o test

When I disassemble this, I get :

push   %ebp
mov    %esp,%ebp
sub    $0x10,%esp
movl   $0x16,-0x8(%ebp)
movl   $0x7,-0x4(%ebp)
mov    $0x0,%eax
leave  
ret 

But if I apply optimizations like :

gcc test.c -o test -O3

all I get in disassembly is :

push   %ebp
xor    %eax,%eax
mov    %esp,%ebp
pop    %ebp
ret 

Without Optimizations the values 22 and 7 where clearly visible in disassembly and I could clearly understand how the code worked but where are those values now after optimizations ? how is the code working now ? Please somebody explain .


Solution

  • Since your code doesn't effectively do anything externally visible that would have unpredictable side effects, the creation of the struct is simply eliminated completely, and now all your code does is returning 0 from main().

    (If you tell the compiler that it does indeed need to create the struct because it may be modified by someone/something else, it won't get rid of the code. Declare your variables as volatile and you'll see it in the assembler.)