Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
coredump Avatar asked Dec 08 '22 21:12

coredump


2 Answers

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.

like image 92
jcoder Avatar answered Dec 24 '22 00:12

jcoder


Not in C++. They will not be executed at compile time just like that - unless the compiler magically does it. However, this cannot be forced.

However, with C++11, you can use constexpr to ensure it is evaluated at compile time, eg:

constexpr int get_five() {return 5;}

Thus, you can rewrite your function as:

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

Note that you do not have to worry if the arguments to this function are not always constant.

From Wikipedia:

If a constexpr function or constructor is called with arguments which aren't constant expressions, the call behaves as if the function were not constexpr, and the resulting value is not a constant expression. Likewise, if the expression in the return statement of a constexpr function does not evaluate to a constant expression for a particular invocation, the result is not a constant expression.

This means that foo(1,1) will be constant, but:

int i,j;
cin >> i >> j;
foo(i,j) // this is not constant

Reference: http://en.wikipedia.org/wiki/C%2B%2B11#constexpr_-_Generalized_constant_expressions

like image 39
ronalchn Avatar answered Dec 23 '22 22:12

ronalchn