如何重新编写代码来实现相同的测试,但便携避免该警告?
AFAIK,INT_MAX并且SIZE_MAX不定义成一个始终是> =比其他的,因此以下功能的使用,以检测问题从转换int到size_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;
}
Run Code Online (Sandbox Code Playgroud)
不同的编译器使用各种机制来抑制警告.我正在寻找便携式解决方案.
上述解决方案不可移植,gcc不幸的是这种方法有副作用:-Wtype-limits现在在此代码之后启用了警告,可能已启用也可能未启用.不知道如何恢复-Wtype-limits设置.
你可以替换这个:
assert((unsigned)size <= SIZE_MAX);
Run Code Online (Sandbox Code Playgroud)
通过:
#if INT_MAX > SIZE_MAX
assert((unsigned)size <= SIZE_MAX);
#endif
Run Code Online (Sandbox Code Playgroud)
如果#if条件为假,则assert条件始终为真且assert不必要.在(unsigned)演员阵容(可能)有必要避免对符号和无符号数之间的比较警告.
警告:我没有测试过这个.(为了完全测试它,我需要访问一个int比更宽的系统size_t,我从来没有见过这样的系统.)