The define Preprocessing Directive in C
Part 39 of the Complete C Course
Foreword: The define Preprocessing Directive in C
By: Chrysanthus Date Published: 22 Jun 2024
Introduction
Constant
Consider the following statement:
const int myIdent = 25;
myIdent holds the value 25, and that cannot be changed. In other words, myIdent is constant. myIdent can alternatively be made constant using the define preprocessing directive, as follows.
#define myIdent 25
Notice that there is no semicolon at the end of the line. There is also no = operator. The define expression begins with #. All preprocessing directives begin with #. Preprocessing directives are usually coded at the top of the program.
Also note that there is no type specifier. The type can be any type. It can be float, int, char string literal, etc. However, the printf() function call has to specify the type. The following program illustrates this for a string:
#include <stdio.h>
# define str "I love you"
int main()
{
printf("%s\n", str);
return 0;
}
The first argument of the predefined pringf() function call, has "%s" for string. The output is: "I love you".
Note: the define or undef (see below) preprocessing directives, or any other directive, must be the first expression in a new line, beginning with #, not necessarily at the very beginning of the new line.
The undef Preprocessing Directive
After defining a variable, the same variable can be un-defined, for it to hold another new value. This uses the undef preprocessing directive. The following program illustrates this:
#include <stdio.h>
#define ch1 'A'
int main()
{
printf("%c\n", ch1);
#undef ch1
#define ch1 'B'
printf("%c\n", ch1);
return 0;
}
The syntax for "undef" is the same as that for "define". The output is A B, with each character on a separate line.
The rest of the preprocessing directives are: #if, #ifdef, #ifndef #elif, #else, endif, #include, #line, #error, #pragma, #new-line. Their meanings and usage are left as research for the reader.