c++coptimization

Function calls with constants optimization in C/C++


If you have function call with constants, it has no side effects and it is not dependent on anything, like the following:

int foo(int a,int b)
{         
  return a+b;   
}

Does the function get inlined? Or, perhaps is the function evaluated at compile-time, with the result of this evaluation inserted in place of the function call?


Solution

  • I tried compiling this using a fairly old gcc -

    #include <iostream>
    
    int foo(int a,int b)
    {
        return a+b;
    } 
    
    
    int main()
    {
        std::cout << foo(100, 123) ;
    }
    

    And main compiled to this -

    LFB1439:
        subq    $8, %rsp
    .LCFI1:
        movl    $223, %esi
        movl    $_ZSt4cout, %edi
        call    _ZNSolsEi
        xorl    %eax, %eax
        addq    $8, %rsp
        ret
    

    So it compiled the addition at compile time getting 223.

    Obviously the results depend on your code and compiler but this shows that it can and does both inline and compute the addition at compile time if it can.