#define to implement constants

The preprocessor allows us to customize the language.

For example to replace { and } of C language to begin and end as block-statement delimiters (as like the case in PASCAL) we can achieve this by writing:

# define begin {
# define end     }

During compilation all occurrences of begin and end get replaced by corresponding { and }. So the subsequent C compilation stage does not know any difference!

#define is used to define constants.

The syntax is as follows:

# define <literal> <replacement-value>

literal is identifier which is replaced with replacement-value in the program.

For Example,

#define MAXSIZE 256
#define PI 3.142857

The C preprocessor simply searches through the C code before it is compiled and replaces every instance of MAXSIZE with 256.

# define FALSE 0
# define TRUE !FALSE

The literal TRUE is substituted by !FALSE and FALSE is substituted by the value 0 at every occurrence, before compilation of the program. Since the values of the literal are constant throughout the program, they are called as constant.

The syntax of above # define can be rewritten as:

# define <constant-name> <replacement-value>

Let us consider some examples,

# define M 5
# define SUBJECTS 6
# define PI 3.142857
# define COUNTRY INDIA

Note that no semicolon (;) need to be placed as the delimiter at the end of a # define line. This is just one of the ways that the syntax of the preprocessor is different from the rest of C statements (commands). If you unintentionally place the semicolon at the end as below:

#define MAXLINE 100; /* WRONG */

and if you declare as shown below in the declaration section,

char line[MAXLINE];

the preprocessor will expand it to:

char line[100;]; /* WRONG */

which gives you the syntax error. This shows that the preprocessor doesn’t know much of anything about the syntax of C.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: