2

I have a question regarding inline function.

#include <iostream> using namespace std; class A { public: inline void fun() { int i=5; cout<<i<<endl; } }; int main() { A a1; int i = 2; a1.fun(); cout<<i<<endl; return 0; } 

In above program, when function fun() was called, the compiler should have made copy of this function and insert into main function body because it is inline.

So, I have a question, Why doesn't compiler give an error of variable int i; being re-declared?

4
  • It's the generated code that is inline, not the source, i.e. it's not like a macro replacement. Commented Aug 27, 2017 at 9:15
  • 2
    Note: the inline keyword does not guarantee that the function will be inlined. In fact, most compilers ignore it completely for inlining desitions. It has other uses, like ODR, but it no longer has any meaning for actual inlining. At best it's a inlining hint, but I don't think any modern compilers use it for even that any more. Commented Aug 27, 2017 at 9:18
  • 4
    It means nothing in this code anyway as functions declared inline of class definition are already inline Commented Aug 27, 2017 at 9:22
  • I know that msvc++ supports a __force_inline keyword that will do exactly what it sounds like. If you are certain that a function should be inlined you can guarantee it this way. I find it unlikely that someone will judge better than the compiler and it will not permit the compiler to choose based on target architecture. In any case, one should always measure the performance difference if __forceinline is used. Commented Aug 27, 2017 at 13:55

1 Answer 1

4

You seem confused about scopes. They're not "within the same" scope

You can declare multiple variables with the same name at different scopes. A very simple example would be the following:

int main() { int a; // 'a' refers to the int until it is shadowed or its block ends { float a; // 'a' refers to the float until the end of this block } // 'a' now refers to the int again } 

Inline expansion is not pure text replacement (as opposed to macros).

Whether a function is inlined or not has no effect on semantics Otherwise the program would behave differently depending on whether the function was inlined or not, and return statements would not behave properly at all.

Sign up to request clarification or add additional context in comments.

Comments