0

I've been trying to understand the output of below C++ code snippet.

union A
{
    struct B
    {
        int a : 5;
        int b : 4;
        int c : 3;
    }b;
    unsigned char e;
}U;

int main()
{
    U.e = 10;
    std::cout << "a - " << U.b.a << std::endl;
    std::cout << "b - " << U.b.b << std::endl;
    std::cout << "c - " << U.b.c << std::endl;

    system("pause");
    return 0;
}

output: a - 10 b - 0 c - 0

Thanks, Rehman

bruno
  • 32,421
  • 7
  • 25
  • 37
  • where do you see a nested union ? `U.e = 10`also set *a* because it is the first member of the *struct* but its value depends on the endianness and the size of an *int*, knowing *U* was first fill with 0 being a global var. If you are in little endian *a* values 10, if you are in big endian and *int* have 32 bits and *char* have 8 bits the value of *a* is 0x0A000000 – bruno Jan 02 '21 at 08:35
  • `std::cout` is C++ and not C – klutt Jan 02 '21 at 08:37
  • @bruno Huh? No, it was I who edited them? https://stackoverflow.com/posts/65537243/timeline – klutt Jan 02 '21 at 08:39
  • @klutt we did at the same time for the tag ;-), but after I did for the body – bruno Jan 02 '21 at 08:40
  • @bruno Ah, I see – klutt Jan 02 '21 at 08:40
  • @klutt even the type of the attributes are reversed I think it is duplicate of https://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c do you agree or found better ? – bruno Jan 02 '21 at 08:47
  • @user12716429 does https://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c help you to understand ? – bruno Jan 02 '21 at 08:50
  • thanks for help. i have understood the code – user12716429 Jan 02 '21 at 08:58
  • Does this answer your question? [Purpose of Unions in C and C++](https://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c) – bruno Jan 02 '21 at 09:14

1 Answers1

1

Your code is UB, as reading non active member of an union is UB, so all bet are off.

Even if no UB, bitfield handling is compiler specific, so result would not be portable.

Jarod42
  • 203,559
  • 14
  • 181
  • 302