Q.The textbook explains that a simple macro is used to define a constant. It gives the general form #define identifier string and the following examples:
#define COUNT 200
#define FALSE 0
#define CAPITAL "BANGALORE"
#define PI 3.1415926
#define COUNT 200
#define FALSE 0
#define CAPITAL "BANGALORE"
#define PI 3.1415926
[!TLDR]
#define creates a symbolic constant by textual substitution done by the preprocessor before the compiler ever sees the code.
The #define directive is a preprocessor compiler directive (not a statement); it is placed at the beginning of the program, before main(), begins with the # symbol in column one, and does not end with a semicolon. Its general form is:
#define identifier string
When such a line is included, the preprocessor replaces every occurrence of the identifier in the source code with the string, before compilation. The four examples each define a constant — COUNT is 200, FALSE is 0, CAPITAL is the text "BANGALORE", and PI is 3.1415926.
A short complete program shows the substitution in action:
#include <stdio.h>
#define PI 3.1415926
int main(void)
{
float r = 2.0, area;
area = PI * r * r;
printf("area = %f\n", area);
return 0;
}
Before compilation the preprocessor rewrites PI * r * r as 3.1415926 * r * r, so the program computes the area of a circle of radius 2.
[!ANSWER]
#define performs preprocessor text substitution: COUNT to 200, FALSE to 0, CAPITAL to "BANGALORE" and PI to 3.1415926. For the demo program above the output is area = 12.566370.
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.