1

I'm trying to initialize the members of candy like this.

#include <iostream>
#include <string>

struct CandyBar
{
std::string Brand;
float weight;
int cal;
};

int main()
{
CandyBar candy[3];
candy[0] = {"toe foe", 30.2f, 500};
candy[1] = {"lays", 2.1f, 10};
candy[2] = {"fin", 40.5f, 1000};
return 0;
}

But it gives me a syntax error near the opening brace i know this is wrong but is there a way like this to initialize a array of struct. And can someone explain why is the above code wrong.

10
  • Any reason for no constructor? Commented Jun 27, 2013 at 4:55
  • Your code works fine as-is in C++11. Commented Jun 27, 2013 at 5:13
  • @bames53, Huh, didn't think that worked with std::string as a member unless there was a constructor to call, but it does on GCC at least :) Commented Jun 27, 2013 at 5:16
  • 2
    Your code should compile with C++11. Commented Jun 27, 2013 at 5:27
  • 2
    @yuan there is nothing explicit in 5.17 assignment, but what I think happens is that copy assignment: semantically, the RHS initializar list converts to a CandyBar temporary, which is then used for assignment. Commented Jun 27, 2013 at 6:43

2 Answers 2

2

You're not initializing the array, you're making assignments to its elements. If you do use an initializer, it will work fine:

CandyBar candy[3] = {
    {"toe foe", 30.2f, 500},
    {"lays", 2.1f, 10},
    {"fin", 40.5f, 1000}
};
Sign up to request clarification or add additional context in comments.

Comments

2
CandyBar candy[3] = {
 {"toe foe", 30.2f, 500},
 {"lays", 2.1f, 10},
 {"fin", 40.5f, 1000}};

You can do this.

This style can only be used in the initialization stage, i.e when you create the variable. It cannot be used to assign the value later. (pre C++11)

3 Comments

You can use this style at the assignment stage too. CandyBar is an aggregate.
@juanchopanza any proof in standard? 8.5.1 Aggregates didn't talk about the assignment at all
@juanchopanza I have made it clearer that the statement applies to < C++11. From the fact that the question exists, I take it thats where the OP is from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.