0

I am reading The C++ PL by Bjarne Stroustrup. It states about unions that:

"Unions are sometimes misused for ‘‘type conversion.’’ This misuse is practiced mainly by programmers trained in languages that do not have explicit type conversion facilities, so that cheating is necessary. For example, the following ‘‘converts’’ an int to an int∗ simply by assuming bitwise equivalence:

union Fudge {
int i;
int∗ p;
};
int∗ cheat(int i)
{
Fudge a;
a.i = i;
return a.p; // bad use
}

This is not really a conversion at all. On some machines, an int and an int∗ do not occupy the same amount of space, while on others, no integer can have an odd address. Such use of a union is dangerous and nonportable."

Can someone explain in simpler words what the author means here? Why is it not a conversion? If not like this then how do we achieve type-conversion?

timrau
  • 22,578
  • 4
  • 51
  • 64
Birbal
  • 61
  • 7
  • 1
    Read up on *casts*. – Jesper Juhl Feb 17 '18 at 17:07
  • If you are used to a modern desktop machine, where addresses are plain integers more often than not, Bjarne's words may not make much sense, since you don't get get a "feel" for them. But try the same trick with an `int` and a `float`. You'll soon see why value conversions don't equate to treating a bit pattern as a different type. This [floating point reference](https://en.wikipedia.org/wiki/Floating-point_arithmetic) may come in handy. – StoryTeller - Unslander Monica Feb 17 '18 at 17:08
  • 1
    The last paragraph from the quote explains why this isn't a conversion. Is there a specific part of that explanation that you don't understand? – Code-Apprentice Feb 17 '18 at 17:10
  • This code used to work for a while, 32-bit flat memory models provided an island of stability that allowed such cheats and get away with it. That doesn't work anymore, in 64-bit code an int commonly takes 4 bytes of storage and a pointer takes 8. That is hammering a square peg in a round hole, you'll lose the edges. – Hans Passant Feb 17 '18 at 17:13
  • Okay I get it why this type conversion won't work...but why would we like to do such type conversion from int to (int*)? What use could it be? – Birbal Feb 17 '18 at 17:24
  • It's not a conversion because the standard says so. It is undefined to read `.p` when `.p` is not what you wrote to. – Lightness Races in Orbit Feb 17 '18 at 17:27
  • 1
    Why would we like to do such a conversion? Well, _I_ wouldn't. This is a contrived example. Non-contrived examples also exist. – Lightness Races in Orbit Feb 17 '18 at 17:27

0 Answers0