#define
The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type. Syntax:
#define token value
Example:
#include <stdio.h> #define PI 3.14 main() { printf("%f",PI); } Output: 3.140000
#include <stdio.h> #define MIN(x,y) ((x)<(y)?(x):(y)) void main() { printf("Minimum between 20 and 30 is: %d\n", MIN(20,30)); } Output: Minimum between 20 and 20 is: 20
#undef
The #undef preprocessor directive is used to undefine the constant or macro defined by #define. Syntax:
#undef token
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
#include <stdio.h> #define number 20 int square=number*number; #undef number main() { printf("%d",square); } Output: 400
#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present. Syntax:
#ifdef MACRO
//code
#endif
Syntax with #else:
#ifdef MACRO //successful code #else //else code #endif
#ifdef example
see a simple example to use #ifdef preprocessor directive.#include <stdio.h> #define NOINPUT void main() { int b=0; #ifdef NOINPUT b=4; #else printf("Enter b:"); scanf("%d", &b); #endif printf("Value of b: %d\n", b); getch(); } Output: Value of b: 4
#include <stdio.h> void main() { int b=0; #ifdef NOINPUT b=4; #else printf("Enter b:"); scanf("%d", &b); #endif printf("Value of b: %d\n", b); } Output: Enter b:10 Value of b: 10