我要通過Andrew Koenig和Barbara E. Moo編寫的「Accelerated C++」一書,我對第2章中的主要示例有一些疑問該代碼可以被總結如下,並且在不警告/錯誤被編譯具有克++:安全地比較unsigned int和std :: string :: size_type
#include <string>
using std::string;
int main()
{
const string greeting = "Hello, world!";
// OK
const int pad = 1;
// KO
// int pad = 1;
// OK
// unsigned int pad = 1;
const string::size_type cols = greeting.size() + 2 + pad * 2;
string::size_type c = 0;
if (c == 1 + pad)
{;}
return 0;
}
然而,如果我通過int pad = 1;
取代const int pad = 1;
,g ++編譯器將返回一個警告:
warning: comparison between signed and unsigned integer expressions [-Werror=sign-compare]
if (c == 1 + pad)
如果我用替換,g ++編譯器不會返回警告。
我明白了爲什麼G ++返回警告,但我不知道這三個以下幾點:
- 是安全的,以便與
std::string::size_type
比較使用unsigned int
?編譯器在這種情況下不會返回警告,但我不確定它是否安全。 - 爲什麼編譯器沒有給出原始代碼
const int pad = 1
的警告。編譯器是否自動將變量pad
轉換爲unsigned int
? - 我也可以用
string::size_type pad = 1;
替代const int pad = 1;
,但是在我看來,變量pad
的含義並沒有真正與鏈接大小相關聯。不過,在這種情況下,這是否是避免在比較中使用不同類型的最佳方法?
從msdn:'basic_string :: size_type' =>'typedef typename allocator_type :: size_type size_type;'=>無符號整數類型,可以表示字符串中元素和索引的數量。 (https://msdn.microsoft.com/library/5ddehwe8.aspx)。所以使用unsinged int可能是一個好方法 – Fefux
@Fefux我不相信微軟作爲C/C++標準的授權源。他們對這些年的標準有足夠的「創造性」解釋...... – skyking
'if((int)c == pad + 1)' – i486