by Dinesh Thakur Category: Type And Variables

Macros are small functions (generally single line functions) which may be dealt with the help of preprocessor directive #define. Here, we shall discuss only the directive #define which is also used to define constants. A macro may or may not have parameters. An advantage of using a macro is that if a program involves a large number of the function calls of a small function the overburden of function calls can make the program inefficient; in case of macro, the code is substituted wherever the macro occurs. Thus, a programmer does not have to repeat the code again and again in the source code of the program while the function call is eliminated. However, a disadvantage of using macro is that data types are not included in the macro nor are these checked by the compiler. A few illustrations of macros are given below.

(i) A macro for finding greater of two numbers may be defined as below.

#define max(x,y) (x>y ? x:y)

In the above expression some spaces are important. There is at least one space between #define and max (x, y) but there is no space between max and the left bracket '('.Again there is at least one space between max (x, y) and the expression (x > y ? x : y)

(ii) A macro for display of a message is illustrated below.

#define Message "Hello World!"

Note that there is at least one space between #define and Message and between Message and the string "Hello World!"

(iii) A macro for finding area of circle is illustrated as given below.

#define Area(R) 3.14159*(R)*(R)

You will notice that there is at least one space between #define and Area (R) and between Area (R) and 3. 14l59*R*R. However, there is no space between Area and the left parenthesis '('. The variable R is put in parentheses so that there is no error even if R is substituted as R + A. Application of two macros is illustrated in Program: one finds the greater of two numbers, while the other displays a message.

Illustrates defining a macro in a program

# include <stdio.h>

#define max(m,n,p) ((m>n? m:n)>p? (m>n? m:n): p)
# define Message "See I have done it."
void main()
  int x,y,z;
  printf("Write three integers :");
  scanf("%d %d %d", &x, &y, &z);
  printf("The maximum of the three numbers is %d.\n" ,max(x,y,z));
  printf("%s\n", Message);
}   Pre-Processor Directive in C

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content