难道一元+运算符做的类型转换?

编程入门 行业动态 更新时间:2024-10-23 17:27:22
本文介绍了难道一元+运算符做的类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

难道一元+运算符做的类型转换?

本文发布于:2023-10-04 05:59:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!