Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct with char arrays initialize to zero in unusual way

Came across a non-common bit of c++ initialization code that seems to work fine with the following...

struct sfoobar { char bar[10]; char foo[10]; };
...
sfoobar x { 0 };

Is this an acceptable method for initializing these char arrays to zero?

like image 506
user2048106 Avatar asked Apr 24 '18 03:04

user2048106


People also ask

How do you initialize a char array to 0?

char ZEROARRAY[1024] = {0}; The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup: memset(ZEROARRAY, 0, 1024);

Does C initialize structs to 0?

You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.

How initialization of a character array can be done in C?

You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)


1 Answers

This is valid in C++. As the effect sfoobar x { 0 }; would initialize all the elements of x.bar and x.foo to 0.

According to the rule of aggregate initialization, the braces for nested initializer lists could be omitted,

the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

then sfoobar x { 0 }; means initializing the 1st element of x.bar to 0, and

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).

So all the remaining elements, including the 2nd to 10th elements of x.bar and all the elements of x.foo would be value-initialized to 0 too.

like image 192
songyuanyao Avatar answered Oct 13 '22 23:10

songyuanyao