详谈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 妈妈生日祝福语简短励志