2

I was messing around with structs and noticed that of the following two examples, only one worked. Here they are:

struct Test
{ 
    char *name; 
    int age; 
}; 

Test p1 = { "hi", 5 };
//works


struct Test
{ 
    char *name; 
    int age; 
}p1; 

p1 = { "hi", 5 };
//error

How come the first one compiles and the second one doesn't? Isn't p1 an object of Test either way? Thanks.

2 Answers 2

5

In the first example you are initializing a struct with two values in a "brace initialization." There is no support in C++ (or C) for assigning to a struct using a brace-enclosed list.

You could, however, create a new struct using brace initialization, then assign it to the old struct (p). C++ (and C) does support assignment of one struct to another of the same type.

For example, in C++11:

p1 = Test{ "hi", 5 };
Sign up to request clarification or add additional context in comments.

4 Comments

Okay, makes sense. Thanks.
The syntax for C is slightly different. I believe you need something like p1 = (struct Test){"hi", 5"}.
And C (actually C99) also supports even nicer syntax: p = (struct XXX){.a=2, .b="def"};
@nimrodm: As a C++ user, don't remind me how nice C99 struct init is. :)
2

The following does work with C++11: (Compile with g++ -std=c++11 init.cpp)

#include <iostream>

struct XXX {
    int a;
    const char *b;
};

int main() {
    XXX x;
    x = XXX{1, "abc"};
    // or later...
    x = XXX{2, "def"};

    std::cout << x.b << std::endl;

    return 0;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.