Home >Backend Development >C++ >C/C++ preprocessing directives
In C or C, we find different lines starting with (#) symbol. These are called preprocessing directives. These lines are processed in the preprocessing stage before compiling the code. Here we will see three different types of preprocessing directives. These are -
Sometimes we define some macros in the program. Use conditional compilation directives. We can check if the macro is defined. We can also control them. So if a macro is defined, certain tasks are performed, otherwise other similar tasks are performed.
Conditional compilation directives are similar to #ifdef-#elif-#else-#endif. Each #ifdef block must end with an #endif. #elif or #else are optional.
#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 }
MY_MACRO is defined, value is: 10
Use line control directives by typing #line. Sometimes we get some errors regarding preferred line numbers. We can use this command to update the line number. If we place it and change the current row to 200, then the rows after that will move from 201.
#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; }
Current line is: 5 Hello World Current line is: 202
The error directive is used to display errors before compilation. It is assumed that a macro should be defined, but if it is not defined, an error message can be displayed. This can be achieved using #error.
#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 }
#error MY_MACRO should be defined
The above is the detailed content of C/C++ preprocessing directives. For more information, please follow other related articles on the PHP Chinese website!