我正在研究C ++语言,我的书中的一条建议是不要混合使用带符号和无符号类型的表达式,因为带符号的类型将转换为无符号的类型。

例如 :

unsigned int u = 10;
int a = 42;
std::cout << u - a << std::endl; // here the value will wraps around


在此程序之后,如果我尝试使用typeid终止a的类型,则结果为int,为什么?
为什么a的类型不是更无符号的,而是返回int?

最佳答案

该变量不会转换为无符号。它的值将转换为无符号以便在表达式中使用。也就是说,当您这样做时:

std::cout << u - a << std::endl;


a创建一个临时的,无名的无符号int,然后从u中减去它。好像您已经这样做:

std::cout << u - (unsigned int)a << std::endl;


或这个:

unsigned int __nameless__ = a;
std::cout << u - __nameless__ << std::endl;


除了__nameless__变量实际上不存在于该表达式之外。

关于c++ - 在C++中涉及有符号和无符号类型的表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25590305/

10-11 22:41
查看更多