Benefits of declaring a function as “inline”?

前端 未结 10 1903
天涯浪人
天涯浪人 2020-12-09 14:01

Every time I read about the \"inline\" declaration in C it is mentioned that it is only a hint to the compiler (i.e. it does not have to obey it). Is there any benefit to ad

10条回答
  •  孤城傲影
    2020-12-09 14:30

    It provides a simple mechanism for the compiler to apply more OPTIMIZATIONS.
    Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.

    Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.

    Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it. I could see a situation like this making a detectable difference:

    inline int aplusb_pow2(int a, int b) {
      return (a + b)*(a + b) ;
    }
    
    for(int a = 0; a < 900000; ++a)
        for(int b = 0; b < 900000; ++b)
            aplusb_pow2(a, b);
    

提交回复
热议问题