c++ inline function?

前端 未结 6 485
终归单人心
终归单人心 2020-11-27 12:49

Why should i do something like this:

inline double square (double x) { return x*x;}

instead of

double square (double x) {          


        
6条回答
  •  一个人的身影
    2020-11-27 13:14

    Yes there is a difference. https://isocpp.org/wiki/faq/inline-functions.

    When you specify that a function is inline you are causing the compiler to put the code of the method in where ever it is being called.

    void myfunc() {
      square(2);
    }
    

    is identical to

    void myfunc() {
       2 * 2;
    }
    

    Calling a function is good for code clarity, but when that function is called the local state has to be pushed to the stack, a new local state is setup for the method, and when it is done the previous state needs to be popped. That is a lot of overhead.

    Now if you up your optimization level, the compiler will make decisions like unrolling loops or inlining functions. The compiler is still free to ignore the inline statement.

提交回复
热议问题