c++ - 对数组的元素编号感到困惑是-1

标签 c++

我正在阅读这里的代码: https://github.com/chenshuo/muduo/blob/master/muduo/base/Date.cc

但我对这两行感到困惑:

char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1];

(void) require_32_bit_integer_at_least; // no warning please

他们的目的是什么?

char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1];

int getJulianDayNumber(int year, int month, int day)
{
  (void) require_32_bit_integer_at_least; // no warning please
  int a = (14 - month) / 12;
  int y = year + 4800 - a;
  int m = month + 12 * a - 3;
  return day + (153*m + 2) / 5 + y*365 + y/4 - y/100 + y/400 - 32045;
}

最佳答案

代码要求 int 至少为 32 位宽。 如果不是这种情况并且 sizeof(int) 小于 32 位,您将收到如下错误:

error: size of array 'require_32_bit_integer_at_least' is negative

线

(void) require_32_bit_integer_at_least; // no warning please

似乎是为了避免“未使用的变量”警告。但是,由于数组是全局的和非静态的,编译器无论如何都不会生成警告。 要知道全局非静态变量确实未被使用,需要检查整个项目中的所有翻译单元(源文件)。


正如@MartinBonner 所提议的,为了使其更清晰和更易于使用,我们可以定义一个“静态断言”宏:

#define STATIC_ASSERT(EXPR, MSG) typedef char static_assertion_##MSG[(EXPR) ? 1 : -1]

并按如下方式使用它:

STATIC_ASSERT(sizeof(int) >= sizeof(int32_t), int_is_less_than_32_bit);    

const bool foo = true;
STATIC_ASSERT(foo, foo_is_not_true); 

关于c++ - 对数组的元素编号感到困惑是-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385247/

相关文章:

c++ - 无法推断出 T[] 的模板参数

c++ - 通过 SDL 像素数据生成 Magick++ 动画

c++ - 像这样传递 Const 时出错

c++ - 链接到多个项目时的全局数据的多个实例

c++ - 派生类中的运算符==永远不会被调用

c++ - OpenMP 中的信号

c++ - 打包 OpenCV Dll 以分发 C++ DLL

c++ - 找不到 Dyld 符号错误

python - 使用 Tensorflow C++ API 执行在 skflow 中训练的模型

c++ - 通过2个字段查找特定对象的 vector 元素