๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด/C++ ์‘์šฉ

[C/C++] unsigned์™€ signed์˜ ๊ฐ’ ๋น„๊ต ์ฃผ์˜

by ์„œ์•„๋ž‘๐Ÿ˜ 2022. 3. 23.

 

 

 

unsigned ์ž๋ฃŒํ˜•๊ณผ signed ์ž๋ฃŒํ˜•์€ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฒ”์œ„๊ฐ€ ๋‹ค๋ฆ…๋‹ˆ๋‹ค.

๊ทธ๋ž˜์„œ ๊ฐ™์€ ์ž๋ฃŒํ˜•์ด๋ผ๋„ unsigned์™€ signed์˜ ๊ฐ’์„ ๋น„๊ตํ•  ๋•Œ๋Š” ์ปดํŒŒ์ผ๋Ÿฌ์—์„œ warning์„ ๋ฑ‰์–ด์ค๋‹ˆ๋‹ค.


unsigned int uVal = 3;
int nVal = -1;

if (uVal > nVal)
{
    printf("unsigned 3 is bigger than signed -1\n");
}
else
{
    printf("signed -1 is bigger than unsigned 3\n");
}


์–ด๋–ค ๊ฒฐ๊ณผ๋ฅผ ๋ณด์—ฌ์ค„๊นŒ์š”?


์ถœ๋ ฅ ๊ฒฐ๊ณผ๋Š” else๋ฌธ์ธ "signed -1 is bigger than unsigned 3"์ด ์ถœ๋ ฅ ๋ฉ๋‹ˆ๋‹ค.


ํ†ต์ƒ์ ์œผ๋กœ uVal์ด nVal๋ณด๋‹ค ํฌ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๊ฒ ์ง€๋งŒ unsigned์™€ signed๋ฅผ ๋น„๊ตํ•  ๋•Œ๋Š” ๋‘˜ ์ค‘ ๋” ํฐ ๋ฒ”์œ„์ธ unsigned๋กœ ๋ณ€ํ™˜๋˜์„œ ๋น„๊ตํ•˜๊ธฐ ๋•Œ๋ฌธ์— unsigned int(3)๊ณผ unsigned int(-1)์ด ๋น„๊ต๋œ ๊ฒ๋‹ˆ๋‹ค.

unsigned int์— ์Œ์ˆ˜ ๊ฐ’์ด ๋“ค์–ด๊ฐ€๋ฉด unsigned int max(4294967295)๊ฐ’์ด ๋“ค์–ด๊ฐ€๊ธฐ ๋•Œ๋ฌธ์— else๋ฌธ์ด ์ถœ๋ ฅ๋์Šต๋‹ˆ๋‹ค.


์œ„ ๊ฐ’์„ ์šฐ๋ฆฌ ๋ˆˆ์— ๋ณด์ด๋Š” ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด

if((int)uVal > nVal) ๋กœ ๋น„๊ตํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด ์ฒซ๋ฒˆ์งธ ์ถœ๋ ฅ๋ฌธ์ด ์ถœ๋ ฅ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.


gcc/g++, MSVC++ ์ปดํŒŒ์ผ๋Ÿฌ์—์„œ ๋ชจ๋‘ ๋™์ผํ•œ ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ–ˆ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€