被人忽略的 signed 关键字

本文深入探讨了C/C++中signed关键字在char与bit-fields使用过程中的实际作用,指出其在特定场景下并非冗余,而是具有隐晦的意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道且经常用到 unsigned 关键字,但有没有想过,与此对应的 signed 关键字有啥用?

int i = 0;
signed int i = 0;

这俩有区别吗?没区别,看起来,signed 完全是个累赘。


真的是这样吗?

我查阅了 C++11 的标准文档(草稿N3690),发现一些端倪:

3.9.1 Fundamental types

Objects declared as characters(char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-de?ned whether a char object can hold negative values. Characters can be explicitly declared unsigned or signed. Plain char, signed char, and unsigned char are three distinct types, collectively called narrow character types. A char,a signed char,and an unsigned char occupy the same amount of storage and have the same alignment requirements(3.11); that is,they have the same object representation. For narrow character types, all bits of the object representation participate in the value representation. For unsigned narrow character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types. In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-de?ned.

标准规定的很清楚,char, signed charunsigned char 是三种不同的类型。 char 会根据具体实现场景,而决定到底是 signed 还是 unsigned.

再看看 C11 的标准文档(ISO/IEC 9899:201x)呢?

6.7.2 Type speci?ers

Each of the comma-separated multisets designates the same type, except that for bit-?elds, it is implementation-de?ned whether the speci?er int designates the same type as signed int or the same type as unsigned int.

看来,bit-fields (位域) 也存在同样的问题。(位域的概念可能也有点偏,经常写比较底层的接口或协议童鞋应该熟悉,可参考这里)


结论

在 C/C++ 中,signed 关键字绝大多数情况下都是累赘,但对于上述所言的两种情况,即在 charbit-fields 的使用过程中,还是有比较隐晦的作用的。

给自己提个醒,总是好的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值