我要通过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