c - 是否可以在编译时检测 C 中的范围错误

标签 c gcc compiler-warnings

我知道,当 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/

相关文章:

c++ - 使用 C++ 编译器包含 C 头文件时的警告

c++ - 关于未使用值的警告并不总是出现

Clang -Wconditional-uninitialized on struct member array 赋值

ios - 我可以安全地抑制 "common"项目的整数符号转换编译器警告吗?

c - 需要有关 fork 中 processIDs 的 2 个特定问题的帮助(在类似 unix 的系统上)-C 语言

c - 使用 GnuTLS 构建 wget?

c - 如何计算链表中的节点数?为什么输出显示节点数为 '2' ?

C++ 精确计时器 time.h boost::posix_time

c - 为什么 *ptr.member 错误而 (*ptr).member 正确?

iphone - iPhone/iPod touch/iPad 上的标准 c 库头文件