3,387 views
2 votes
2 votes
Use of macro instead of function is recommended.
(a) when one wants to reduce the execution time
(b) when there is a loop with a function call inside
(c) when a function is called in many places in a program
(d) In (a) and (b) above

Can some one explain how option 'b' is true?

1 Answer

Best answer
6 votes
6 votes
If the function call is withing a loop, you're gonna call it for the number of times loop runs. Say, for example, loop runs 1000 times, it will result in time and memory overhead of creating and initializing 1000 activation records in call stack. If you use macro, the function call is replaced by the actual code defined by macro so no its same as executing those lines of code without additional function calling or memory usage.

PS: If function gets inlined -- which normally happens for most small functions, then it has the same effect as macros. Also, there is no guarantee that macros (inlined functions also) will always be faster than functions. This is because they can lead to an increase in code size, which can lead to potential Instruction cache miss. The best place to use macros is where a function has to be executed with different parameters and these parameters are known while writing the code -- this can avoid the execution overhead of processing that parameter.
selected by

Related questions

1 votes
1 votes
1 answer
1
Desert_Warrior asked May 16, 2016
695 views
#include <stdio.h #define crypt(s,t,u,m,p,e,d) m s u t #define begin crypt(a,n,i,m,a,t,e) int begin() { printf("Hello\n"); return 0; }Options are :(a) Hello (b) Link erro...
1 votes
1 votes
2 answers
2
Anushka Basu asked Jul 21, 2016
1,816 views
Please explain the solution.The output is 11 7 0#define MAX(x,y) (x) (y) ? (x) : (y) main() { int i = 10, j = 5, k = 0; k == MAX(i++, ++j); printf("%d %d %d", i,j,k); }W...