#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)
int main()
{
int radius;
float area;
printf("Enter the radius: ");
scanf("%d", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);
return 0;
}
C PREPROCESSOR AND MACROS
The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled. These transformations can be inclusion of header file, macro expansions etc.
All preprocessing directives begins with a # symbol. For example,
#define PI 3.14
Including Header Files
The #include preprocessor is used to include header files to a C program. For example,
#include <stdio.h>Here, "stdio.h"
is a header file. The #include
preprocessor directive replaces the above line with the contents of stdio.h
header file which contains function and macro definitions.
That's the reason why you need to use #include <stdio.h>
before you can use functions like scanf()
and printf()
.
Macros using #define
You can define a macro in C using #define preprocessor directive.
A macro is a fragment of code that is given a name. You can use that fragment of code in your program by using the name. For example,
#define c 299792458 // speed of light
Here, when we use c in our program, it's replaced by 3.1415.
Example 1: Using #define preprocessor
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
You can also define macros that works like a function call, known as function-like macros. For example,
#define circleArea(r) (3.1415*r*r)
Every time the program encounters circleArea(argument)
, it is replaced by (3.1415*(argument)*(argument))
.
Suppose, we passed 5 as an argument then, it expands as below:
circleArea(5) expands to (3.1415*5*5)Example 2: Using #define preprocessor