Programming Language

Difference Between Inline Functions and Macros

Macros are fragments of code that have been given a name. Whenever the macro name is used within the program, the preprocessor automatically expands it before runtime. This means that whenever we use a macro name in the program, it is automatically replaced with the macro’s code by the preprocessor.

Inline functions however are functions that are explicitly defined to be inline. Whenever an inline function is called, the compiler parses it and copies the functions code at that location.

By definition, both macros and inline functions seem quite familiar and are easy to confuse. However, the major difference between them is the manner in which they are handled at compilation time.

How Are They Different?

  • Macros are copied without compilation (error-prone) whereas inline functions are copies of compiled functions (which makes them error-free).
  • A macro is just code that is “copy-pasted” by the preprocessor which means that there is no type checking for the parameters passed or returned from a macro. Therefore, there are chances of side effects such as mismatches.
  • Inline functions are parsed directly by the compiler and not by the preprocessor. This makes sure that inline functions are type checked which ensures that their execution.
  • Macros can be easily used in context where you don’t expect them to be since they are lines of un-compiled code – this can result in problems and errors that are found by the compiler at the time of runtime (when the code is incorrectly placed in the wrong context).
  • Inline functions are similar to regular functions (just a little difference of syntax) in C++. Therefore, there is also a difference in the ways in which a macro and an inline function is declared/written.
  • Macros are more flexible than inline functions because macros can expand other macros.
  • Inline functions provide a scope for variables whereas macros do not.
  • Inline functions need to be compiled by specific compilers that are configured to parse them otherwise, these functions may malfunction.

 

Even though the two terms, macros and inline functions, may seem familiar, they are quite different in context and implementation. Both of them are used for reducing the number of incurred function calls in C++ but each has its own unique manner in which it is declared and handled.

Leave a Reply