zl程序教程

您现在的位置是:首页 >  其它

当前栏目

详谈signed关键字

关键字 详谈 signed
2023-06-13 09:15:41 时间

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

复制代码代码如下:


inti=0;
signedinti=0;

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

真的是这样吗?

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

3.9.1Fundamentaltypes

复制代码代码如下:


Objectsdeclaredascharacters(char)shallbelargeenoughtostoreanymemberoftheimplementation"sbasiccharacterset.Ifacharacterfromthissetisstoredinacharacterobject,theintegralvalueofthatcharacterobjectisequaltothevalueofthesinglecharacterliteralformofthatcharacter.Itisimplementation-definedwhetheracharobjectcanholdnegativevalues.Characterscanbeexplicitlydeclaredunsignedorsigned.Plainchar,signedchar,andunsignedchararethreedistincttypes,collectivelycallednarrowcharactertypes.Achar,asignedchar,andanunsignedcharoccupythesameamountofstorageandhavethesamealignmentrequirements(3.11);thatis,theyhavethesameobjectrepresentation.Fornarrowcharactertypes,allbitsoftheobjectrepresentationparticipateinthevaluerepresentation.Forunsignednarrowcharactertypes,allpossiblebitpatternsofthevaluerepresentationrepresentnumbers.Theserequirementsdonotholdforothertypes.Inanyparticularimplementation,aplaincharobjectcantakeoneitherthesamevaluesasasignedcharoranunsignedchar;whichoneisimplementation-defined.

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

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

6.7.2Typespecifiers

复制代码代码如下:
Eachofthecomma-separatedmultisetsdesignatesthesametype,exceptthatforbit-fields,itisimplementation-definedwhetherthespecifierintdesignatesthesametypeassignedintorthesametypeasunsignedint.

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

结论

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

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