如何重新編寫代碼來執行相同的測試,但便攜式避免警告?如何在沒有警告的情況下測試`int`到`size_t`的轉換「比較始終爲真」?
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;
}
不同的編譯器使用各種機制來壓制警告。我尋找一種便攜式解決方案。
以上解決方案不是便攜式的,但這種方法不幸有副作用:警告-Wtype-limits
,現在可能已啓用或可能未啓用,現在在此代碼後啓用。不知道如何恢復-Wtype-limits
設置。
編號:
Portability of #warning preprocessor directive
Suppress comparison always true warning for Macros?
注意:使用4.8.2 gcc和「gcc -std = c99 -O1 -g3 -pedantic -Wall -Wtratra -Wconversion」。希望它能在許多編譯器上工作。 – chux