Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Nishtha Thakur

In this section we will see what are the differences between macros and functions in C. The macros are pre-processed, so it means that all the macros will be preprocessed while it is compiled. The functions are not preprocessed, but compiled.

In macros no type checking is done, so it may occur some problems for different types of inputs. In the case of functions, this is not done. Also for macros if the inputs are not properly maintained, then it may generate some invalid results. Please check the following program to get the idea about the problem.

Example

#include <stdio.h>
#define SQUARE(x) x * x
int sqr(int x) {
   return x*x;
}
main() {
   printf("Use of sqr(). The value of sqr(3+2): %d\n", sqr(3+2));
   printf("Use of SQUARE(). The value of SQUARE(3+2): %d", SQUARE(3+2));
}

Output

Use of sqr(). The value of sqr(3+2): 25
Use of SQUARE(). The value of SQUARE(3+2): 11

The function and macro, we want both will do the same task, but here we can see that the output are not same. The main reason is when we are passing 3 + 2 as function argument, it converts into 5, then calculate 5 * 5 = 25. For macro it is doing 3 + 2 * 3 + 2 = 3 + 6 + 2 = 11.

So the macros are not recommended for the following problems −

  • There is no type checking

  • Default to debug, as they cause simple replacement

  • Macro don’t have the namespace. So if the macro is defined in one section, it can be used at another section.

  • Macro increases the code length as it is added before the code while preprocessing.

  • Macro does not check any compile time errors.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.