2의 보수 방식의 맹점

아래의 소스를 실행했을 때의 결과는 다음과 같다.

소스
#include <stdio.h>

union TFontStyle
{
struct
{
int useItalic: 1;
int useBold:   1;
int isFixed:   1;
int reserved:  1;
int grayLevel: 4;
int color:    24;
};
int data; 
};

int main()
{
// TFontStyle의 크기를 확인해 본다.
// union이니 보통 4bytes가 나올 것이다.
printf("sizeof(TFontStyle) = %d\n", sizeof(TFontStyle));

{
TFontStyle fontStyle;

// 전체 bit field를 초기화
fontStyle.data = 0;

// 위에서 초기화를 했으니 아마도 0이겠지.
printf("useItalic = %d\n", fontStyle.useItalic);

// 이태릭을 사용하는 것으로 설정.
fontStyle.useItalic = 1;

// 위로 설정한 대로 그대로 비교를 하자.
// 그 결과는?
if (fontStyle.useItalic == 1)
printf("That's the way!!\n");
else
printf("why??!!\n");
}

return 0;
}

결과
sizeof(TFontStyle) = 4
useItalic = 0
why|!  <-- 왜 이것이 출력되지?


딴 부분은 다 문제가 없고 제일 마지막의 if문이 문제인데, 이런 문제(2의 보수를 이용한 음수 표현)때문에 if문의 분기가 예측과는 다르게 나간다면 참으로 잡기 어려운 버그를 만들 수 있을 것이다.

Posted by 안영기

2009/02/15 09:52 2009/02/15 09:52
Response
0 Trackbacks , 5 Comments
RSS :
http://smgal.ismine.net/tc_191/blog1/rss/response/6

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

« Previous : 1 : ... 41 : 42 : 43 : 44 : 45 : 46 : 47 : 48 : 49 : ... 50 : Next »

블로그 이미지

게임 개발을 기반으로 한, 잡다한 개발 기록 저장소

- 안영기

Notices

Archives

Authors

  1. 안영기

Recent Comments

Recent Trackbacks

Calendar

«   2024/03   »
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            

Site Stats

Total hits:
235561
Today:
22
Yesterday:
38