Backo
Backo

Reputation: 18871

Trouble on initializing a struct with the constructor initialization list

I am programming Arduino and I have trouble when using the following code

struct myStruct {
  char variable1[10];
  char variable2[10];
  char variable3[10];

  // Constructor
  myStruct() : variable1({'\0'}), variable2({'\0'}), variable3({'\0'}) {}
};

since I get the following error:

expected primary-expression before '{' token

What is the problem? How can I solve it?

Note: The \0 is used for handling null terminated strings.


BTW: Why the following code works and the above does not?

struct myStruct {
  char variable1[10];
  char variable2[10];
  char variable3[10];
} variable = {{'\0'}, {'\0'}, {'\0'}};;

Upvotes: 0

Views: 1623

Answers (3)

Paul R
Paul R

Reputation: 212969

Assuming you just want to initialise the member variables to empty (C-style) strings, change:

  // Constructor
  myStruct() : variable1({'\0'}), variable2({'\0'}), variable3({'\0'}) {}

to:

  // Constructor
  myStruct() : variable1(""), variable2(""), variable3("") {}

Edit

Apparently some versions of gcc complain about this usage (see comments below) - this appears to be due to a bug in gcc.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361422

Remove parens. Use braces only.

That is, instead of

variable1({'\0'})

write this,

variable1{'\0'}   //removed parens!

If you follow that, your code would look like this:

myStruct() : variable1{'\0'}, variable2{'\0'}, variable3{'\0'} {}

Any compiler that supports C++11 should be able to compile it.


In C++03, write this:

myStruct() : variable1(), variable2(), variable3() {}

That should work for this particular case. That is all you have : value-initialization. C++03 doesn't give you much freedom.

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254461

In C++11, your code should work, although it has rather more brackets than strictly necessary.

In any C++, you could specify value-initialisation to zero-initialise the arrays:

myStruct() : variable1(), variable2(), variable3() {}

If you're being ultra-paranoid, and don't trust '\0' to be equivalent to zero, then you'd have to write to the arrays in the constructor body.

Why the following code works and the above does not?

Because it's always been possible to aggregate-initialise variables in a declaration. It's only since 2011 that it's been possible to do that in a member initialiser.

Upvotes: 0

Related Questions