Namespaces
Variants

Diagnostic directives

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

显示给定的错误信息并使程序成为病式 ,或显示给定的警告信息而不影响程序的有效性 (since C++23)

目录

语法

#error 诊断信息 (1)
#warning 诊断信息 (2) (自 C++23 起)

说明

1) 遇到 #error 指令后,实现会显示消息 diagnostic-message 并使程序变为非良构(编译停止)。
2) (1) 相同,但程序的有效性不受影响,编译过程将继续。

diagnostic-message 可由多个单词组成,且无需使用引号括起。

注释

在C++23标准化之前, #warning 指令已作为符合规范的扩展功能被众多编译器在所有模式下提供。

示例

#if __STDC_HOSTED__ != 1
#   error "Not a hosted implementation"
#endif
#if __cplusplus >= 202302L
#   warning "Using #warning as a standard feature"
#endif
#include <iostream>
int main()
{
    std::cout << "The implementation used is hosted\n";
}

可能的输出:

The implementation used is hosted

参考文献

  • C++23 标准 (ISO/IEC 14882:2024):
  • 15.8 错误指令 [cpp.error]
  • C++20 标准 (ISO/IEC 14882:2020):
  • 15.8 错误指令 [cpp.error]
  • C++17 标准 (ISO/IEC 14882:2017):
  • 19.5 错误指令 [cpp.error]
  • C++14 标准 (ISO/IEC 14882:2014):
  • 16.5 错误指令 [cpp.error]
  • C++11 标准 (ISO/IEC 14882:2011):
  • 16.5 错误指令 [cpp.error]
  • C++03 标准 (ISO/IEC 14882:2003):
  • 16.5 错误指令 [cpp.error]
  • C++98 标准 (ISO/IEC 14882:1998):
  • 16.5 错误指令 [cpp.error]

参见

C 文档 关于 诊断指令