C变量类型断言

ale*_*lex 15 c

uint32_t fail_count = 0;

...

if(is_failed)
    if(fail_count < UINT32_MAX - 1 )
        ++fail_count;
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是此代码易碎。明天,我可能会将fail_countfrom 的类型更改为uint32_tint32_t而忘记更新UINT32_MAX

有什么方法可以在我编写s 的函数中断言fail_counta 吗?uint32_tif

PS 1-我知道在C ++中很容易,但是我正在寻找一种C方式。

PS 2-与使用编译器警告相比,我更喜欢使用两个断言。通过检查数字大小sizeof应该可以,但是有什么方法可以区分类型是否为无符号?

Rya*_*ing 22

从C11开始,您可以使用通用选择宏根据表达式的类型产生结果。您可以在静态断言中使用结果:

#define IS_UINT32(N) _Generic((N), \
  uint32_t: 1, \
  default: 0 \
)

int main(void) {
  uint32_t fail_count = 0;
  _Static_assert(IS_UINT32(fail_count), "wrong type for fail_count");
}
Run Code Online (Sandbox Code Playgroud)

您当然可以在regular中使用结果assert(),但是_Static_assert在编译时会失败。

更好的方法是基于类型调度比较,再次使用泛型选择:

#include <limits.h>
#include <stdint.h>

#define UNDER_LIMIT(N) ((N) < _Generic((N), \
int32_t: INT32_MAX, \
uint32_t: UINT32_MAX \
) -1)

int main(void) {
  int32_t fail_count = 0;

  if (UNDER_LIMIT(fail_count)) {
    ++fail_count;
  }
}
Run Code Online (Sandbox Code Playgroud)