If you define this in the header file, then there is a high probability that it will be embedded. If the integral constants of compilation time are used as arguments, the compiler should be able to perform this function at compile time.
Despite the lack of such a guarantee, you must trust your compiler. They optimize your code very well. If you want the function to be executed at compile time, you can add constexpr overload (C ++ 11 only):
constexpr int foo(int a,int b){ return a+b; }
I tried the following snippet:
int add(int a, int b) { return a + b; } int main() { return add(5, 2); }
When compiled using GCC and the -O3 flag, it compiles as follows:
0x08048300 <+0>: mov $0x7,%eax 0x08048305 <+5>: ret
Therefore, you can see that it actually executes at compile time.
source share