Search code examples
c++inline-functions

Why using inline function in c++ doesn't grow binary size?


I have written this code:

inline int a_plus_b_power2(int a, int b) {
  return (a + b) * (a + b); 
}

int main() {
  for(int a = 0; a < 9999999999999; ++a)
    for(int b = 0; b < 999999999999; ++b)
      a_plus_b_power2(a, b);  

  return 0;
}

but why the binary of this program doesn't differ with this program:

inline int a_plus_b_power2(int a, int b) {
  return (a + b) * (a + b); 
}

int main() {
  for(int a = 0; a < 9; ++a)
    for(int b = 0; b < 9; ++b)
      a_plus_b_power2(a, b);  

  return 0;
}

Solution

  • You are confusing function inlining with loop unrolling:

    Loop unrolling means transforming

    for (int i = 0; i < 4; i++)
      a(i);
    

    into

    a(0); a(1); a(2); a(3);
    

    while function inlining means transforming

    void a(int i) { cout << i; }
    
    for (int i = 0; i < 4; i++)
      a(i);
    

    into

    for (int i = 0; i < 4; i++)
      cout << i;
    

    Compilers do have options to enable loop unrolling (look at -funroll-loops and related options for gcc), but unless you poke them really hard, most of them will be very reluctant to unroll 999999999999 iterations... (the resulting binary would be multiple terabytes).