As its name suggests, pre-processing is a phase that occurs prior to the compilation of a program. The C preprocessor is basically a macro processor (the name macro is abbreviations for longer constructs), which is used by the compiler to transform a program before starting the actual compilation process.
Pre-processor commands are distinguished by the hash symbol (#). In every program, we have used, #include <stdio.h>
, which is nothing but a preprocessor directive. Let us start with an example.
In the following program, we are using a macro to set the value of PI and declare a variable to store radius. Later, we are calculating the perimeter of a circle.
Now, compile the program and save the temporary files, using the following command.
gcc circle.c --save-temps
Look at the content of circle.i file, which is generated as intermediate file.
The line, #include
#include <filename> is a command which tells the preprocessor to consider the content of the file to be included as part of the program.
Macros are used to define something in a program and reduce typing effort to make an abbreviation of a long construct. For example, as the value of PI is fixed and may be used in many places, it can be defined as a macro instead of a global variable, as the value of a variable can be altered within a program.
The most important feature of macros is that they are not numerical constants, but are strings that are replaced before compilation by the preprocessor.
Example
Macros cannot be defined in more than a single line. But it can be defined anywhere within a program (except within double quote of a string).
Some macros are defined within header files. For example, EOF , NULL are defined in stdio.h .
Macro Function
More advanced use of macros (macro function) is permitted by the preprocessor. A macro function accepts parameters and returns a value. Let us discuss with an example.
#define ABS(x) ((x) < 0) ? -(x) : (x)
This function returns the positive number, for example, ABS(-5) and ABS(5), both will return 5.
In this context, run the following program and check the result.
The results of SQAUARE(5) and SQUARE(5.5) are as expected. Whereas the result of SQUARE(5 + 10) is not according to the expectation. The reason behind this result is in this macro call, the value of x is replaced by 5 + 10. Hence, the expression becomes 5 + 10 * 5 + 10 . But expected expression is (5 + 10) * (5 + 10) . So the code should be updated as follow:
For condition checking, the preprocessor if-else can be used as follow:
To check whether a macro is defined or not, you may use the following macro
To undefine a macro
In the following program, we have used many macros together.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.