Abdelrahman Ramadan
Abdelrahman Ramadan

Reputation: 153

Does the compiler do the same action for all inline function calls?

Does C++ compiler take different decisions regarding inlining two different calls for the same inline function ?

consider a code like this:

inline func(int x) {
    return x + (x << 1) + (x << 2) + (x << 3) + (x << 4);
}

int main() {
    int y = func(1) + func(2) + func(3) + func(4);
    for(int i = 0; i < 100000000; ++i)
        y += func(i % 10);
    cout << y << endl;
    return 0;
}

would the compiler do the same action with the calls before the loop and the one inside the loop ? if we considered code length along with speed optimization then the calls before the loop shouldn't be inlined and the one inside should.

Upvotes: 4

Views: 184

Answers (1)

Akira
Akira

Reputation: 4473

It depends on your compiler. Let's say you use gcc 5.4.0 with -O2 optimization level. The first line inside the main function

int y = func(1) + func(2) + func(3) + func(4);

will be calculated at compile time due to integer literals and the code inside the for loop will be inlined. But if you use another compiler or another optimization level the outcome can be different.

If you wish to inspect the assembly output of your code use the Compiler Explorer which is an online and free tool.

Upvotes: 4

Related Questions