pre-processing in c++

Image result for c++Now we have learned basics of C, but yet we do not know why we #include <stdio.h> is written on the 1st line of every program. Today we will know things related to this.

In the beginning we learned that after we write a program, computer converts it to machine language. That process is called compilation. Compilation process goes through many steps. Today we will learn about those steps then why we write #include <stdio.h> in the beginning of every program.

We know that printf is a function. This function is defined(declared) in stdio.h file. When program is compiled, in 1st step compiler replaces #include <stdio.h> with content of stdio.h file. This process is called pre-processing. By doing this program gets to know definition of printf function, hence can run this function successfully otherwise it will give compile error that printf function not defined.

stdio means Standard Input and Output. In this file(stdio.h) all function used for input/output are defined. printf used to print output on console whereas scanf used to read input from console. Both functions are declared in stdio.h file.         

Pre-processing

In a program any line starting with # is called pre-processor. In 1st step of compilation process compiler modifies them. #include is a pre-processing directive which replaces it with content file given. There are some more pre-processing directive which are described below.

#define ABC 1
#define is used to define constant. If #define ABC 1 is present in program, in 1st step of compilation ABC will be replaced with 1 in the program. #define is called macro too.

#define SUM(a,b) (a+b)
This is also a macro which can take parameter. If use this in program, SUM(x,y) will be replaced with (x+y) in the program.

#ifdef xyz
...
#endif
If xyz is defined anywhere using #define then program between #ifdef and #endif will be compiled otherwise it will be removed.

Note: One pre-processor should be written in one line only and nothing else in that line.
We are seeing #include from beginning. Below we will see example of some other pre-processor.

#include <stdio.h>
#define AREA(r) (PI*r*r)
#define PI 3.14159

int
main() {
int
rad = 10;
float
area = AREA(rad);
printf("Area of circle is %f\n", area);

scanf("%d", &r);
return
0;
}


In the program given above AREA(rad) will be replaced with (PI*rad*rad) and then in this PI will be replaced with 3.14159. Note that it is not same as function call. In function call return value should be assigned to area but here AREA(rad) is replaced with (3.14159*rad*rad) and answer is calculated here itself without any function call, that is assigned to area, but effect is same as function call.