How does an inline function differ from a preprocessor macro?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:
In some cases, expressions passed as arguments to macros can be evaluated more than once. http://msdn.microsoft.com/en-us/library/bf6bf4cf.aspx
macros are expanded at pre-compile time, you cannot use them for debugging, but you can use inline functions.
-- good article: http://www.codeguru.com/forum/showpost.php?p=1093923&postcount=1
;
To add another difference to those already given: you can't step through a
#define
in the debugger, but you can step through an inline function.A inline functuion behaves syntactically just like a normal function, providing type safety and a scope for function local variables and access to class-members if it is a method. Also when calling inline methods you must adhere to private/protected restrictions.
First, the preprocessor macros are just "copy paste" in the code before the compilation. So there is no type checking, and some side effects can appear
For example, if you want to compare 2 values:
The side effects appear if you use
max(a++,b++)
for example (a
orb
will be incremented twice). Instead, use (for example)Macros are ignoring namespaces. And that makes them evil.
In GCC (I'm not sure about others), declaring a function inline, is just a hint to the compiler. It is still up to the compiler at the end of the day to decide whether or not it includes the body of the function whenever it is called.
The difference between in-line functions and preprocessor macros is relatively large. Preprocessor macros are just text replacement at the end of the day. You give up a lot of the ability for the compiler to perform checking on type checking on the arguments and return type. Evaluation of the arguments is much different (if the expressions you pass into the functions have side-effects you'll have a very fun time debugging). There are subtle differences about where functions and macros can be used. For example if I had:
Where MACRO_FUNC obviously defines the body of the function. Special care needs to be taken so it runs correctly in all cases a function can be used, for example a poorly written MACRO_FUNC would cause an error in
A normal function could be used with no problem there.