Home > Backend Development > C++ > body text

C/C++ preprocessing directives

王林
Release: 2023-09-08 16:01:02
forward
1158 people have browsed it

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
}
Copy after login

Output

MY_MACRO is defined, value is: 10
Copy after login

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;
}
Copy after login

Output

Current line is: 5
Hello
World
Current line is: 202
Copy after login

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
}
Copy after login

Output

#error MY_MACRO should be defined
Copy after login

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

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template