鍍金池/ 問答/C  C++/ c語言中 等號是如何運作的?

c語言中 等號是如何運作的?

unsigned char c=-1;

-1是按照int類型存儲的常量吧 打印出來的c是直接把-1的補碼模式的最后一個字節(jié)直接抄給c了 c語言的等號就是直接按位照抄么? 把常量賦予變量的時候會不會對常量先轉(zhuǎn)化某種與變量比較搭配的類型再賦予?

回答
編輯回答
夕顏

ISO C 標準中寫到

6.3.1.3 Signed and unsigned integers

When a value with integer type is converted to another integer type
other than _Bool, if the value can be represented by the new type, it
is unchanged. Otherwise, if the new type is unsigned, the value is
converted by repeatedly adding or subtracting one more than the
maximum value that can be represented in the new type until the value
is in the range of the new type. Otherwise, the new type is signed and
the value cannot be represented in it; either the result is
implementation-defined or an implementation-defined signal is raised.

換句話說,unsigned char 的表示范圍是 [0, 255],不能表示 -1,于是將 -1 加上 256 得到 255。

如果是把 signed char 型 -1 轉(zhuǎn)成 unsigned int,則用 -1 加上 4294967296 得到 4294967295。

對硬件來說,從有符號到無符號的轉(zhuǎn)換就是簡單地在前面補符號位或者直接截斷。

2017年3月12日 21:47