C Macros

A macro is a segment of code which has been given a name and whenever the name is used, it is replaced by the contents of the macro.  In C language a macro can be defined by using #define preprocessor directive. There are two types of Macros :

1. Object-like Macros
2. Function-like Macros

1. object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent constant values. For example:
 #define PI 3.14
Example :
#include <stdio.h>

#define PI 3.14

int main() {
  printf("The value of Pi is : %.2f\n", PI);
  return 0;
}
Output :

The value of Pi is : 3.14


2. Function-like Macros

Function-like macros resemble function calls. In function-like macro, the whole function is defined inside macro. For example :
 #define MAX(a, b) ((a>b)?(a):(b))
In the above statement the macro named MAX() takes two argument and return the greater one. Lets see The C example code :
#include <stdio.h>

#define MAX(a,b) ((a>b)?(a):(b))

#define MIN(a,b) ((a<b)?(a):(b))

int main() {
  printf("Max between 50 and 80 is : %d\n", MAX(50, 80));
  printf("Min between 120 and 115 is : %d\n", MIN(120, 115));
  return 0;
}
Output :

Max between 50 and 80 is : 80
Min between 120 and 115 is : 115


Predefined Macros

There are some predefined macros which are readily for use in C programming.

Predefined macro Value
__DATE__ String containing the current date.
__FILE__ String containing the file name.
__LINE__ Integer representing the current line number.
__STDC__ If follows ANSI standard C, then value is a nonzero integer.
__TIME__ String containing the current date.

Example :
#include <stdio.h>

int main() {

  printf("Date : %s\n", __DATE__);
  printf("Time : %s\n", __TIME__);
  printf("File : %s\n", __FILE__);
  printf("Line : %d\n", __LINE__);
  printf("ANSI : %d\n", __STDC__);

  return 0;
} 
Output :

Date : Aug 3 2018
Time : 21:18:35
File : predef_macro.c
Line : 8
ANSI : 1


Next Topic :