by Dinesh Thakur Category: Preprocessor Directives

Macros may also be created by #define. Here the identifier can have parameters but types of parameters are not mentioned.

#define identifier(parameters) replacement_text

The following should be noted:

(i) There is a space after #define and after closing bracket ')' of parameters.

(ii) There should not be any blank space between identifier and starting bracket '('.

For instance, for determining the greater of two numbers, a macro may be defined in the following way:

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

The last expression has been placed between a pair of brackets but it could also be written as follows:

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

In the above code it should be made certain that there is no blank space in the expression x>y?x: y. One has to be very careful about spaces when dealing with macros. There must be at least one space between #define and identifier, in this case max(x,y), and at least one space between closing right bracket of max(x,y) and replacement text, i.e., (x >y? x: y).But, there should be no space between max and opening left bracket ( '('after max). However, it is much better to define such a macro as given below. It takes care of the situation in which the arguments x and y are put as x+m and y+n. The expression between parentheses is taken as one unit. So, spaces inside brackets ( ) do not matter.

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

In the above declaration the directive #define creates a macro-a function to obtain the greater of the given two values. The values may be integers or floating point numbers or characters. There is no type checking and it is equally applicable to all types. Its application is illustrated in Program.

# include <stdio.h>

# define max(m,n) (m >n ? m : n) // definition of macro
void main()
{
    int A, B;
    float x,y;
    clrscr();
    printf("Enter two integers.");
    scanf("%d%d",& A,& B);
    printf("Enter two float numbers.");
    scanf ("%f%f", &x, &y);
    printf("Greater of the twp numbers A and B = %d\n", max(A ,B ));
    pri ntf("Greater of the to float numbers= %f\n", max(x,y));
}
The expected output is as given below. The explanation provided above makes the output self explanatory.

Preprocessor Directive #define



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.