详谈signed 关键字
我们都知道且经常用到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的使用过程中,还是有比较隐晦的作用的。
给自己提个醒,总是好的。
热门推荐
10 情侣祝福语古文简短独特
11 酒店伴娘祝福语简短
12 晚上甜蜜的祝福语简短
13 给新娘简短的祝福语
14 当爸爸的简短祝福语
15 洛宁新年祝福语大全简短
16 新年祝福语简短搞笑幽默
17 结婚祝福语大全简短霸气
18 新人结婚祝福语简短高端