Home  >  Article  >  Backend Development  >  C/C++ preprocessing directives

C/C++ preprocessing directives

王林
王林forward
2023-09-08 16:01:021142browse

C/C++ 预处理指令

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 -

  • Conditional compilation
  • Line control
  • Error directive

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.

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

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.

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 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.

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

The above is the detailed content of C/C++ preprocessing directives. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete