強制類型轉換表達式,結果是左值嗎?
操作系統:WIN7 32bit
編譯器: VS2010 32bittest1:
#include &
int main()
{
int i = 256;// 編譯成功,強制轉換後表達式為左值,地址與原來相同
printf("%p %p
", (float)i, i);
printf("%f %d", (float)i, i);
printf("%p %p
", (long)i, i);
printf("%ld %d", (long)i, i);
printf("%p %p
", (short)i, i);
printf("%d %d", (short)i, i);
printf("%p %p
", (char)i, i);
printf("%d %d", (char)i, i);
// 編譯失敗,強制轉換後表達式為非左值
//printf("%p %p
", (long long)i, i); // 失敗
printf("%lld %d", (long long)i, i); // 成功
//printf("%p %p
", (double)i, i); // 失敗
printf("%f %d", (double)i, i); // 成功
getchar();
return 0;
}
運行結果:
0022F848 0022F848
256.000000 2560022F848 0022F848
256 2560022F848 0022F848
256 2560022F848 0022F848
0 256256 256
256.000000 256
請求解答:
強制類型轉換結果,轉換類型尺寸&<=原始數據尺寸 結果為左值,取地址後發現轉換後的左值地址與原始數據地址一樣,轉換類型尺寸 &> 原始數據尺寸 結果為非左值。難道這是未定義行為?
其中int轉換為float,地址也沒變。同時將轉換後的浮點數與原始數據列印,可以正確列印,因為沒有副作用,內存中仍為原始數據,那轉換後的數據在哪?地址為何與原始數據相同?test2:
#include &
int main()
{
int i;// 強制轉換後表達式,結果為左值,作為前綴++、--的操作數
i = 256;
printf("%f %d", ++((float)i), i); // ++((float)i),不是想像中的257.000000
i = 256;
printf("%f %d", --((float)i), i);
i = 256;
printf("%d %d", sizeof((float)i), i);
getchar();
return 0;
}
運行結果:
1.000000 1065353216
-1.000000 -1082130432
4 256
請求解答: int轉換float類型後,結果為左值,同時地址與原始數據相同,通過前綴++、--改變轉換結果,可以看到,原始數據被更改成了float型值的位模式+1或-1了。 可是test1中float類型的轉換結果與int類型的原始數據,地址相同,都可以同時正確輸出。這個時候的位模式如何兼容兩種類型的正確列印?
首先你應該列舉出來你的編譯環境(操作系統環境、編譯器及其版本),方便復現。而根據我的測試,在Mac OS X Clang 3.7 / GCC 5.3中,你的成功轉換例子均提示錯誤,所以這對我來說是一個不可復現的例子。
而你能通過,我能猜到的莫過於微軟不按標準常規的實現了,所以我搜索了一下Visual Studio Type Cast L-Value. 然後發現的確是微軟的擴展:Type-Cast Conversions
若是從語言標準來說的話,可以參考C++標準 5.4:
The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.哥們,以後開Bug附上詳細的環境啊,包括你工作中也是。推薦閱讀:
※C語言里如何按需生成函數指針數組?
※sizeof(void*)的大小到底由何決定?
※C++new運算符調用operator new 分配內存後, 構造函數調用及指針類型的轉換在哪裡完成?
※有哪些較好的 C 語言程序源碼可供新手臨摹參考?
※新手入門c語言應該下載那個軟體?