Reputation: 1635
#include <iostream>
struct people
{
int id;
} person; // that part
int main()
{
person = {3};
std::cout << person.id;
return 0;
}
I want to ask you about initializing a structure (well, not initialization...creating structure type...I don't really know how do you call this). Once I've seen some keyword after structure, like the "person" here. All without any typedef.
I did a little research and found out that it's used to define a variable directly after the structure.
However, my code I posted above doesn't compile - it says syntax error, missing semicolon and crap like that meaning the expression is not valid.
What is this used for, and how to use this?
Upvotes: 1
Views: 2071
Reputation: 254501
Once I've seen some keyword after structure, like the "person" here.
It's not a keyword, it's a name. You're allowed to declare variables of a class type in the same statement that defines the type, if you like. It's equivalent to two separate declarations:
struct people
{
int id;
};
people person;
However, my code I posted above doesn't compile
It sounds like either your compiler doesn't support C++11 (specifically, assignment from a braced list), or you're compiling with it disabled.
If you can't use C++11, then you'll have to assign each member separately:
// person = {3}; // C++11 only
person.id = 3;
or declare and initialise a local object and assign from that:
people temp = {3};
person = temp;
or initialise it in its declaration, rather than deferring until main
:
struct people
{
int id;
} person = {3};
Upvotes: 1
Reputation: 409206
You can't use the structure initialization syntax in a normal assignment, it has to be done when you declare your variable:
struct people
{
int id;
} person = { 3 };
If you have a C++11 compatible compiler, you can use the uniform initialization syntax to copy later though:
person = people { 3 };
Upvotes: 7
Reputation: 55887
struct people
{
int id;
} person; // that part
person is the global object of type people
.
person = {3};
Is incorrect in C++03 and correct in C++11, since {3}
will be treated like people{3}
Upvotes: 2