c++optimization

Do modern compilers optimize the x * 2 operation to x << 1?


Does the C++ compiler optimize the multiply by two operation x*2 to a bitshift operation x<<1?

I would love to believe that yes.


Solution

  • Actually VS2008 optimizes this to x+x:

    01391000  push        ecx  
        int x = 0;
    
        scanf("%d", &x);
    01391001  lea         eax,[esp] 
    01391004  push        eax  
    01391005  push        offset string "%d" (13920F4h) 
    0139100A  mov         dword ptr [esp+8],0 
    01391012  call        dword ptr [__imp__scanf (13920A4h)] 
    
        int y = x * 2;
    01391018  mov         ecx,dword ptr [esp+8] 
    0139101C  lea         edx,[ecx+ecx] 
    

    In an x64 build it is even more explicit and uses:

        int y = x * 2;
    000000013FB9101E  mov         edx,dword ptr [x] 
    
        printf("%d", y);
    000000013FB91022  lea         rcx,[string "%d" (13FB921B0h)] 
    000000013FB91029  add         edx,edx 
    

    This is will the optimization settings on 'Maximize speed' (/O2)