简体   繁体   中英

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.

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.

How c compiler interprets this values 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.

Moreover m.floatVal, m.intVal gets evaluated different values depending on which variable I initialised first.

m.floatVal = 3; first gets something 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++. Having written to intVal , reading floatVal is undefined behaviour. Having written to floatVal , reading intVal is undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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