经过 Carl Norum 的编辑以包含适当的标准引用。
C 标准状态
If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
是否有编译器开关可以保证整数溢出时的某些行为?我想避免鼻恶魔。特别是,我想强制编译器在溢出时换行。
为了唯一性,我们假设标准是C99,编译器是gcc。但我会对其他编译器(icc、cl)和其他标准(C1x、C89)的答案感兴趣。事实上,只是为了惹恼 C/C++ 人群,我什至会感谢 C++0x、C++03 和 C++98 的答案。
注意:国际标准 ISO/IEC 10967-1 可能与此处相关,但据我所知,它仅在信息性附件中提及。
最佳答案
-ftrapv
This option generates traps for signed overflow on addition, subtraction, multiplication operations.
-fwrapv
This option instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation. This flag enables some optimizations and disables other. This option is enabled by default for the Java front-end, as required by the Java language specification.
关于c - C 中的整数溢出 : standards and compilers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679047/