Monday, January 20, 2020

#define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.
Syntax:

#define token value

 
Let's see an example of #define to define a constant.

#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}

 
Output:

3.140000

Let's see an example of #define to create a macro.

#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}

 
Output:

Minimum between 10 and 20 is: 10

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.
Syntax:
#undef token

 
Let's see a simple example to define and undefine a constant.

#include <stdio.h>
#define PI 3.14
#undef PI
main() {
printf("%f",PI);
}

 
Output:
Compile Time Error: 'PI' undeclared
The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.
Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

#include <stdio.h>
#define number 15
int square=number*number;
#undef number
main() {
printf("%d",square);
}

 
Output:

225

No comments:

Post a Comment