Macros in C

Macros allow replacement of the identifier by using a statement or expression. The replacement text is called the macro body. C uses macros extensively in its standard header files, such as in getchar(), getc().


#define CUBE(x)  x*x*x      //A
#include <stdio.h>
int main ()
    int k = 5;
    int j = 0;
    j = CUBE(k);            //B  j = k*k*k
    printf ("value of j is %d\n", j);      //C
    return 0;


  1. You can define the macro CUBE as in statement A.
  2. The macro can be defined by using parameters, but that is not mandatory.
  3. The parameter name that is used in a macro definition is called the formal parameter. In this example, it is x.
  4. x*x*x is called the macro body.
  5. There should not be any spaces between the macro name and the left parenthesis.
  6. CUBE(k) in statement B indicates a macro call.
  7. An argument such as k, which is used for calling a macro, is called an actual parameter.
  8. While expanding the macro, the actual parameter is substituted in the formal parameter and the macro is expanded. So you will get the expansion as j = k*k*k.
  9. The value of j is calculated as 125.
  10. Since macro expansion is mainly a replacement, you can use any data type for the actual parameter. So, the above macro works well for the float data type.

Points to Remember

  1. A macro is used when you want to replace a symbol with an expression or a statement.
  2. You can define macros by using parameters.

You may also like...