4

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.

  • 2
    https://godbolt.org/g/twc0Qw – Borgleader Jun 08 '17 at 19:24
  • 3
    What the compiler does is completely down to the compiler's implementation. It could inline both, either, or neither. –  Jun 08 '17 at 19:25
  • 4
    A compiler is free to do any transformation of the code that preserves observable behavior. Different compilers may very well do different things with this program. If you are curious about a particular compiler with particular optimization settings, compile your program with that compiler and those settings, and examine the generated machine code. – Igor Tandetnik Jun 08 '17 at 19:25
  • 1
    Some good reading on the subject: http://www.drdobbs.com/inline-redux/184403879 One apropos quote: "We write inline on a function, but when inlining is performed it actually is done to a function call. This distinction is important because the very same function can (and often should) be inlined at one call site but not at another" – Fred Larson Jun 08 '17 at 19:26
  • 1
    Related: The `inline` keyword has nothing to do with the compiler inlining the function. See https://stackoverflow.com/questions/1759300/when-should-i-write-the-keyword-inline-for-a-function-method – Miles Budnek Jun 08 '17 at 19:57

1 Answers1

4

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.

Akira
  • 4,385
  • 3
  • 24
  • 46