-3

I am reading The C++ Programming Language by Bjarne Stroustrup. It states on unions:

"Unions are occasionally used deliberately to avoid type conversion. One might, for example, use a Fudge to find the representation of the pointer 0:

union Fudge{
    int i;
    int* p;
};

int main()
{
    Fudge foo;
    foo.p= 0;
    cout<< "the integer value of the pointer 0 is" << foo.i<< ´\n´;
} "

I get that this code fragment gives the representaion of pointer 0. But how is it avoiding type-conversion as mentioned in the text?

timrau
  • 22,578
  • 4
  • 51
  • 64
Birbal
  • 61
  • 7
  • It is using a union, thereby avoiding type conversion. – Eljay Feb 17 '18 at 18:36
  • 1
    This is not valid C++ code. And didn't we just have this? https://stackoverflow.com/questions/48843760/conversion-of-int-to-int-using-union posted by you –  Feb 17 '18 at 18:42
  • @NeilButterworth Why – Birbal Feb 17 '18 at 18:43
  • Because the C++ Standard says so. –  Feb 17 '18 at 18:43
  • std::variant might be of assistance, although it might add some overhead – JVApen Feb 17 '18 at 18:43
  • Keep in mind: that book is more than thirty years old. Stroustrup today, in his C++ “Guidelines,” recommends using `reinterpret_cast` instead of this kind of type-punning through a `union`, because both are undefined behavior, but at least the cast makes it explicit. However, in the intervening years, the C (but not C++) language standard made type-punning with `unions` legal. The difficulty with doing it in C++ is that the union member might not be trivially-copyable, and the constructor would not have been called. – Davislor Feb 17 '18 at 18:56

1 Answers1

1

It's called type punning and is explicitly allowed using unions in C but not in C++.

It works (in C) because all members of a union occupy the same memory, so there's really no conversion. You just interpret the bits of the memory differently.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621