简体   繁体   English

通常的算术转换和整数提升

[英]Usual arithmetic conversions and Integer promotion

I'm trying to understand what's going on under the hood of c conversions, and different types promotions and comparing stuff and all of this. 我正在尝试了解c转换,不同类型的促销活动以及所有东西进行比较的情况。

union myUnion{
int intVal;
float floatVal;};

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


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

The first if statement is evaluated to false and the second if statement to true. 第一个if语句的计算结果为false,第二个if语句的计算结果为true。

How c compiler interprets this values m.floatVal, m.intVal. c编译器如何解释此值m.floatVal,m.intVal。 I'm mean what's going on down there, into assembly, because that's going to be run on the CPU. 我的意思是将要进行的组装工作,因为这将在CPU上运行。

Moreover m.floatVal, m.intVal gets evaluated different values depending on which variable I initialised first. 此外,根据我首先初始化的变量,m.floatVal,m.intVal获得了不同的值。

m.floatVal = 3; m.floatVal = 3; first gets something m.intVal = 3; 首先得到的东西m.intVal = 3; first gets something else. 首先得到其他东西。

In the end there is the same value there!?!?!?!?!?!? 最终,那里有相同的值!!!!!!?!?!!!!?

Second example: 第二个例子:

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

How the compiler interprets this mess and what is going on down the assembly? 编译器如何解释这种混乱情况,以及汇编中发生了什么?

Third example: How is a float converted to an int? 第三个示例:浮点数如何转换为整数? Who the bits are all remapped? 谁都被重新映射?

Thank you so much guys! 十分感谢大家! Thank you. 谢谢。

First example: 第一个例子:

union myUnion{
int intVal;
float floatVal;};

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

This is undefined behaviour in c++. 这是c ++中的未定义行为。 Having written to intVal , reading floatVal is undefined behaviour. 写入intVal ,读取floatVal是未定义的行为。 Having written to floatVal , reading intVal is undefined behaviour. 写入floatVal ,读取intVal是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM