Advantage of #define instead of creating a function in embedded

  • A+
Category:Languages

Recently I got to view an embedded code in that they are using

#define print() printf("hello world") 

instead of

void print() { printf("hello world"); } 

My question what is the gain on using #define instead of creating a function?

 


It may be related to performance.

A function call has some overhead (i.e. calling, saving things on the stack, returning, etc) while a macro is a direct substitution of the macro name with it's contents (i.e. no overhead).

In this example the functions foo and bar does exactly the same. foo uses a macro while bar uses a function call.

Advantage of #define instead of creating a function in embedded

As you can see bar and printY together requires more instructions than foo .

So by using a macro the performance got a little better.

But... there are downsides to this approach:

  • Macros are hard to debug as you can't single step a macro

  • Extensive use of a macro increases the size of the binary (compared to using function call). Something that can impact performance in a negative direction.

Also notice that modern compilers (with optimization on) are really good at figuring out when it's a good idea to automatically inline a function (i.e. your code is written with a function call but the compiler decides to inline the function as if it was a macro). So you might get the same performance using function call.

Further, you can use the inline key word as a hint to the compiler that you think it will be good to inline a function. But even with that keyword the compiler may decide not to inline. The only way to make sure that the code gets inline, is by using a macro.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: