C Preprocessors
Preprocessors: are programs that process the source code before compilation.
Preprocessors Directives
Macros
1. Object-like Macros
2. Function-like Macros
Predefined preprocessors
Advantages of using Macros
- Code reuse: By allowing developers to declare a piece of code just once and use it several times.
- Code abbreviation: Macros make it possible to write clear, expressive code that is simpler to read and comprehend the intentions of the programmer.
- Performance Optimization: By minimizing function call overhead, macros may be utilized to optimize code execution.
File inclusion
By the use of #include directive, we provide information to
the preprocessor where to look for the header files. There are two variants to
use #include directive.
1.
#include
<filename> //path
2.
#include
"filename" // directory
The #include <filename> tells the
compiler to look for the directory where system header files are held. In UNIX,
it is \usr\include directory.
1.
#include<stdio.h>
2.
int main(){
3.
printf("Hello C");
4.
return 0;
5. }
Conditional compilation
Using preprocessor directives like #if, #ifdef, #ifndef, #else, and #endif
you can include or exclude parts of
the code during compilation based on defined conditions.
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the preprocessing of these directives is completed.
Example:
#include<stdio.h>
#define A 50
#define B 7
int main()
{
int
result;
#if(A>B)
result=A+B;
printf("sum=%d",result);
#else
result=A-B;
printf("diff=%d",result);
#endif
return
0;
}
Other Directives
1. #undef directive
#undef directive:
#include <stdio.h>
#define VALUE 10
int main() {
printf("Min value is: %d\n", VALUE);
#undef VALUE
#define VALUE 20
printf("Min value after undef and again redefining it: %d\n", VALUE);
return 0;
}
#pragma directive
The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature. Also used to hide the information.
Pragma tokens
Different compilers can provide different usage of #pragma
directive.
The turbo C++ compiler supports following #pragma
directives.
1.
#pragma argsused
2.
#pragma exit
3.
#pragma hdrfile
4.
#pragma hdrstop
5.
#pragma inline
6.
#pragma option
7.
#pragma saveregs
8.
#pragma startup
9.
#pragma warn \\ hide
warning in c programing