2017-10-11 38 views
-1

我想了解c转换的引擎盖下发生了什么,以及不同类型的促销活动和比较东西以及所有这些。通常的算术转换和整数推广

union myUnion{ 
int intVal; 
float floatVal;}; 

if (m.floatVal == m.intVal) 
{ 
    cout << "BINGO!"; 
} 


if (*ptrInt == *ptrInt2) 
{ 
    cout << "BINGO!" << endl << *ptrInt << endl << *ptrInt2; 
} 

第一个if语句的计算结果为false,第二个if语句的计算结果为true。

c编译器如何解释此值m.floatVal,m.intVal。我的意思是那里发生了什么,进入汇编,因为这将在CPU上运行。

此外,m.floatVal,m.intVal根据我首先初始化哪个变量获取不同的值。

m.floatVal = 3;首先得到东西 m.intVal = 3;首先得到别的东西。

最后在那里有相同的价值!?!??????!?

第二个例子:

char minstogo = 0x98; 
if (minstogo <= 7) { 
    cout << "BEAST!"; 
} beast is printed 

char minstogo = 0x98; 
if ((unsigned char)minstogo <= 7) { 
    cout << "BEAST!"; 
} nothing is printed 

char minstogo = 0x98; 
if (minstogo <= (unsigned char)7) { 
    cout << "BEAST!"; 
} beast is printed 

编译器如何解释这个烂摊子,是怎么回事下组装?

第三个示例: float如何转换为int?谁的位都被重映射了?

非常感谢你们!谢谢。

+0

你对工会的理解是错误的:根本没有转换。检查此链接:https://www.tutorialspoint.com/cprogramming/c_unions.htm –

+0

技术上(根据标准)'if(m.floatVal == m.intVal)'调用*未定义的行为*因为只有一个一个'union'的成员可以一次处于活动状态(实际上大多数编译器会像C中的'union'那样对待它们) – UnholySheep

+0

当你有C++标记时,你会一直说C语言。你是在问你的代码暗示的C++吗?还是你真的在问C? –

回答

2

第一个例子:

union myUnion{ 
int intVal; 
float floatVal;}; 

if (m.floatVal == m.intVal) 
{ 
    cout << "BINGO!"; 
} 

这是在C++中未定义的行为。写入intVal后,读取floatVal是未定义的行为。写入floatVal后,读取intVal是未定义的行为。