c - 如何在没有警告 `int` 的情况下测试 `size_t` 到 "comparison is always true"的转换?

标签 c warnings

如何重写代码以实现相同的测试,但可移植避免警告?


AFAIK、INT_MAXSIZE_MAX 没有定义为一个总是 >= 比另一个,因此使用以下函数来检测从 转换的问题intsize_t

#include <assert.h>
#include <stddef.h>
#include <stdint.h>

size_t int_to_size_t(int size) {
  assert(size >= 0);

  #pragma GCC diagnostic ignored "-Wtype-limits"

  // Without the above pragma, below line of code may cause:
  // "warning: comparison is always true due to limited range of data type
  // [-Wtype-limits]"
  assert((unsigned)size <= SIZE_MAX);

  #pragma GCC diagnostic warning "-Wtype-limits"

  return (size_t) size;
}

不同的编译器使用不同的机制来抑制警告。我正在寻找一种可移植解决方案。

上述解决方案不可移植,不幸的是,此 gcc 方法有一个副作用:警告 -Wtype-limits,现在可能已启用也可能未启用在此代码之后启用。不知道如何恢复 -Wtype-limits 设置。

引用:
Portability of #warning preprocessor directive
Suppress comparison always true warning for Macros?

最佳答案

你可以替换这个:

assert((unsigned)size <= SIZE_MAX);

通过:

#if INT_MAX > SIZE_MAX
assert((unsigned)size <= SIZE_MAX);
#endif

如果#if 条件为假,则assert 条件始终为真,并且assert 是不必要的。 (unsigned) 转换(可能)是必要的,以避免有关有符号和无符号操作数之间比较的警告。

警告:我还没有测试过这个。 (要对其进行全面测试,我需要访问一个 int 大于 size_t 的系统,而我从未见过这样的系统。)

关于c - 如何在没有警告 `int` 的情况下测试 `size_t` 到 "comparison is always true"的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235658/

相关文章:

c++ - 直接传递编译选项(绕过CMakeLists.txt)

c - 找出序列中不超过四百万的所有偶数项的总和

swift - 警告 : Expression following 'return' is treated as an argument of the 'return'

MSBUILD/csc : Cleanest way of handling x64 mscorlib warning 1607

c - 警告 : assignment makes point from integer without cast

c - 我如何用C中的线程对数组元素求和?

c - 了解用于模计算的 Intel x86 程序集输出

c - 异步memcached库

c++ - xutility(2227) : warning C4996: 'std::_Copy_impl'

c - 警告 : format ‘%d’ expects argument of type ‘int’ , 但参数 3 的类型为 ‘int *’