In C or C++, we have find different lines stared with (#) symbol. These are called the preprocessing directives. These lines are processed in the preprocessing phase before compiling the code. Here we will see three different types of preprocessing directives. These are −
- Conditional Compilation
- Line control
- Error Directive
Sometimes we define some macros in our program. Using conditional compilation directives. we can check whether the macro is defined or not. We can also control them. So if one macro is defined, then do some task, otherwise do some other task like that.
The conditional compilation directives are like #ifdef-#elif-#else-#endif. Every #ifdef block must be ended with #endif. The #elif or #else are optional.
Example
#include <iostream> #define MY_MACRO 10 using namespace std; int main() { #ifdef MACRO cout << "MACRO is defined" << endl; #elif MY_MACRO cout << "MY_MACRO is defined, value is: " << MY_MACRO; #endif }
Output
MY_MACRO is defined, value is: 10
The line control directive is used by typing #line. Sometimes we get some error with preferred line number. We can update the line number using this directive. If we place this and change the current line as 200, then after that the lines will move from 201 onwards.
Example
#include <iostream> using namespace std; int main() { cout<< "Current line is: " << __LINE__ << endl; #line 200 cout << "Hello" << endl; cout << "World" << endl; cout<< "Current line is: " << __LINE__ << endl; }
Output
Current line is: 5 Hello World Current line is: 202
The error directive is used to show an error before compiling. Suppose one macro should be defined but if that is not defined, we can show an error message. This can be done using #error.
Example
#include <iostream> using namespace std; int main() { #ifdef MY_MACRO cout << "MY_MACRO is defined, value is: " << MY_MACRO; #else #error MY_MACRO should be defined #endif }
Output
#error MY_MACRO should be defined