What is the #error directive in C++?

The #error directive

#error is a Preprocessor Directivecommand that is executed by the compiler before compiling the program that has the following structure:

#error tokens

In the example above, tokens are any sequence of characters separated by spaces. If the compiler encounters an #error directive before compilation, it will halt the compilation and display the tokens as an error in the standard output.

Using the #error directive

The #error directive is normally used to throw an error during conditional compilation.

Take a look:

#include <iostream>
using namespace std;
int main() {
#ifdef PI
double area = PI * 2 * 2;
cout << "Area of a circle of radius 2 is: " << area << endl;
#else
#error PI is not defined
#endif
return 0;
}

In the above example, the PI is not defined error is printed in the standard output because the #ifdef PI evaluates to false, thus, resulting in the execution of the #else clause that contains the #error directive. Here, the #error directive ensures that the compiler will only compile the program if the specified conditions are met; otherwise, the compiler must provide an explanation as to why the program did not compile.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved