我知道,当 gcc 编译文件时,它通常会保留一个变量可以保存的可能值的列表(然后用于各种优化)。我想知道如果该值位于或可能位于范围之外,是否可以创建编译时警告。例如,如果您有函数 foo(int x)
,其中 x 必须介于 0 和 5 之间,然后您有: int y=6; foo(y)
,如果有可能在编译时而不是运行时失败。
最佳答案
是的。下面生成了 GCC 编译 6 与 5 的差异。
#define Jfoo_MIN 0
#define Jfoo_MAX 5
void Jfoo(unsigned x) {
printf("%u\n", x);
}
void Jfoo_test(void) {
const unsigned u = 5;
const unsigned v = 6;
struct {
unsigned x1 :3;
unsigned x2 :3;
} foo = {
// No warning
u + (7 - Jfoo_MAX),
// warning: large integer implicitly truncated to unsigned type [-Woverflow]
v + (7 - Jfoo_MAX),
};
(void) foo;
Jfoo(u);
Jfoo(v);
// warning: expression in static assertion is not an integer constant expression [-Wpedantic]
_Static_assert(u <= Jfoo_MAX, "Too hot u");
// warning: expression in static assertion is not an integer constant expression [-Wpedantic]
// error: static assertion failed: "Too hot v"
_Static_assert(v <= Jfoo_MAX, "Too hot v");
}
关于c - 是否可以在编译时检测 C 中的范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40025632/