难道一元+运算符做的类型转换? [英] Does Unary + operator do type conversions?

查看:197
本文介绍了难道一元+运算符做的类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到现在为止,我认为是没有用的一元 + 运营商。

Till now I was believing that there is no use of unary + operator.

但后来我用下面的例子中遇到:

But then I came across with following example:

char ch;
short sh;
int i;

printf("%d %d %d",sizeof(ch),sizeof(sh),sizeof(i)); // output: 1 2 4

printf("%d %d %d",sizeof(+ch),sizeof(+sh),sizeof(i)); // output: 4 4 4

这是否意味着 + 正在这里做什么类型的转换?

Does it mean + is doing type conversion here?

由于它表现下同

printf("%d %d %d",sizeof((int)ch),sizeof((int)sh),sizeof(i)); // output: 4 4 4

这迫使我觉得 + 正在做类型转换。

This forces me to think + is doing type conversion.

但后来我尝试在双击

double f;
printf("%d %d",sizeof(+f),sizeof((int)f),sizeof(f));  // output: 8 4 8

这迫使我重新思考一元 + 运营商。

This forces me to rethink about unary + operator.

所以我的第二个问题是:一元 + 操作员的sizeof 运营商特殊效果?

So my second question is: does unary + operator has special effect in sizeof operator?

推荐答案

单目+ 的其操作数执行整型的提升,我们可以通过转到C99标准草案看到 6.5.3.3 单目算术运算符的它说(的重点煤矿前进的):

Unary + performs integer promotions on its operand, we can see this by going to the draft C99 standard section 6.5.3.3 Unary arithmetic operators which says (emphasis mine going forward):

一元+运算符的结果是价值的(推动)
  操作数。 整数促销活动操作数执行,并且
  结果具有提升的类型。

The result of the unary + operator is the value of its (promoted) operand. The integer promotions are performed on the operand, and the result has the promoted type.

和部分 6.3.1 算术运算的说道:

如果int可以重新present原始类型的所有值,该值
  转换为int类型;否则,将其转换为一个unsigned int。
  这些被称为整数促销活动 48) 所有其它类型
  由整数提升不会改变。

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48) All other types are unchanged by the integer promotions.

请注意,所有其他的类型是整数促销不变,thereofore的的客人提供的的。这也将持有的浮动的为好,这将不会被提升到的

Note that all other types are unchanged by the integer promotions and thereofore double stays a double. This would also hold for float as well, which would not be promoted to double.

另外请注意,使用%d个中的sizeof 的结果是不确定的行为,因为结果的为size_t 的。正确的格式说明会%祖

Also note that using %d for the result of sizeof is undefined behavior since the result is size_t. the proper format specifier would be %zu.

这篇关于难道一元+运算符做的类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆