How to re-write code to implement the same test, but portably avoid the warning?
AFAIK, INT_MAX
and SIZE_MAX
are not defined to one always being >= than the other, hence the use for the following function to detect problems converting from int
to 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;
}
Different compilers use various mechanisms to squelch warnings. I looking for a portable solution.
The above soluton is not portable and this gcc
method unfortunately has a side-effect: Warning -Wtype-limits
, which may or may not have been enabled is now enabled after this code. Do not know how to restore -Wtype-limits
setting.
Ref:
Portability of #warning preprocessor directive
Suppress comparison always true warning for Macros?