user2565838
user2565838

Reputation: 1

How can I assign value to the struct inside union here?

#include <iostream>
#include <stdint.h>
using namespace std;

union ipv4 {
    struct bytes{
        uint8_t a;
        uint8_t b;
        uint8_t c;
        uint8_t d;
    } bytes;
    uint32_t int32;
};

int main( int argc, char ** argv ) {
    union ipv4 addr;
    addr.bytes = { 192, 168, 0, 96 };
    printf("%d.%d.%d.%d - (%08x)\n",
            addr.bytes.a, addr.bytes.b, addr.bytes.c, addr.bytes.d,
            addr.int32);
    getchar();
    return 0;
}

Error: c:\users\yayun.xie\documents\satmap\c++onlinematerial\exercise files\chap05\union.cpp(18): error C2059: syntax error : '{';

Upvotes: 0

Views: 2649

Answers (1)

Oleksii Shmalko
Oleksii Shmalko

Reputation: 3768

If you export structure declaration out of union, you can write you code like this (this fragment uses compound-literals which is C99's feature C++ forbids)

struct bytes_t {
    uint8_t a;
    uint8_t b;
    uint8_t c;
    uint8_t d;
};

union ipv4 {
    bytes_t bytes;
    uint32_t int32;
};
....
    addr.bytes = (bytes_t){ 192, 168, 0, 96 };

Or, alternatively you can assign fields one by one.

addr.bytes.a = 192;
addr.bytes.b = 168;
addr.bytes.c = 0;
addr.bytes.d = 96;

Or, all in once with declaration-initialization

ipv4 addr = { .bytes = { 192, 168, 0, 96 } };

bytes is first field of union, so you can drop out .bytes = and write just

ipv4 addr = { { 192, 168, 0, 96 } };

With C++11's extended initializer lists, this is also valid:

addr.bytes = { 192, 168, 0, 96 };

By the way, you forgot to include stdio.h to use printf() and getchar().

Upvotes: 1

Related Questions