signed 키워드에 대해 자세히 이야기하다

2197 단어
우리는 모두 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-defined 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-defined.

표준은 명확하게 규정되어 있다.char,signed char와unsigned char는 세 가지 다른 유형이다.char는 구체적인 실현 장면에 따라 signed인지 unsigned인지 결정한다.
C11의 표준 문서(ISO/IEC 9899:201x)를 다시 볼까요?
6.7.2 Type specifiers
 
  
Each of the comma-separated multisets designates the same type, except that for bit-fields, it is implementation-defined whether the specifier int designates the same type as signed int or the same type as unsigned int.

보아하니bit-fields(위역)도 같은 문제가 존재하는 것 같다.(위치의 개념도 약간 편향될 수 있으니 밑바닥의 인터페이스나 협의 구두를 자주 쓰면 익숙해져야 하니 참고하세요)
결론
C/C++에서signed 키워드는 절대 다수의 경우 군더더기이지만 상술한 두 가지 상황, 즉char와bit-fields의 사용 과정에서 비교적 은밀한 작용을 한다.
자신을 깨우쳐 주는 것이 언제나 좋다.

좋은 웹페이지 즐겨찾기