-1

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
M. Alex
  • 49
  • 1
  • 1
  • 5
  • your understanding of union is wrong: there is no conversion at all. Check this link: https://www.tutorialspoint.com/cprogramming/c_unions.htm – Krzysztof Skowronek Oct 11 '17 at 09:06
  • technically (according to the standard) `if (m.floatVal == m.intVal)` invokes *undefined behavior* because only one of the members of a `union` can be active at a time (in practice most compilers will treat them like `union` in C) – UnholySheep Oct 11 '17 at 09:07
  • You keep saying C when you have C++ tagged. Are you asking about C++ as your code suggests, or are you really asking about C? – Passer By Oct 11 '17 at 09:27
  • What will probably be happening is that it is just interpreting the raw bytes of the int as a float or vice-versa, which is going to give completely different values in each case as ints and floats have very different representations. Though of course, as everyone else has pointed out this is undefined behaviour, so it could do literally anything... – Sean Burton Oct 11 '17 at 11:54

1 Answers1

2

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.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142