C++ Structure Initialization

How to initialize a struct in accordance with C programming language standards

In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

How do I initialize a struct in C

I think there is a typo in the declaration of the data member arr. Instead of

char [3]arr;

you have to write

char arr[3];

You may not initialize an array with empty braces. So write for example

struct {
int a;
char arr[3];
.
.
.
} data = {
.a = 1,
.arr = { 0 }
};

In fact it is enough to write

struct {
int a;
char arr[3];
.
.
.
} data = {
.a = 1
};

The array implicitly will be initialized with zeroes.

Initializing a struct to 0

The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].

The second is more readable.

The choice depends on user preference or the one which your coding standard mandates.

[Ref 1] Reference C99 Standard 6.7.8.21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Good Read:

C and C++ : Partial initialization of automatic structure

C++ Structure Initialization

If you want to make it clear what each initializer value is, just split it up on multiple lines, with a comment on each:

address temp_addres = {
0, // street_no
nullptr, // street_name
"Hamilton", // city
"Ontario", // prov
nullptr, // postal_code
};

Initialize a struct in C

This should work:

Rectangle world = {"World", {NULL, NULL}, {0, 0}, {5, 5}, 0};

What does = { 0 }; mean in a structure initialization in C?

Because of the initialization rules of C, it's kind of a universal initializer:
it will initialize numbers or pointers as well as aggregates (=structs/unions) or arrays by setting everything (every member recursively) to zero.

For block scope objects on platforms where the null pointer is "all bits zero" (most platforms), it's equivalent to memset(&object,0,sizeof(object)); and compilers will often generate such a memset call for {0} initializations, particularly when such initializations are applied to a larger object.

C struct initialization using labels. It works, but how?

Here is the section of the gcc manual which explains the syntax of designated initializers for both structs and arrays:

In a structure initializer, specify the name of a field to initialize
with '.fieldname =' before the element value. For example, given the
following structure,

 struct point { int x, y; };

the following initialization

 struct point p = { .y = yvalue, .x = xvalue }; 

is equivalent to

 struct point p = { xvalue, yvalue }; 

Another syntax which has the same meaning, obsolete since GCC 2.5, is 'fieldname:', as shown here:

 struct point p = { y: yvalue, x: xvalue };

The relevant page can be found here.

Your compiler should have similar documentation.

Partially initializing a C struct

When you do this:

struct s myStruct;
myStruct.si = 9;

You are not initializing myStruct. You declare it without an initializer, then run a statement to set one field.

Because the variable is uninitialized, its contents are undefined, and reading it is undefined behavior. This means that seemingly unrelated changes can modify this behavior. In your example adding an extra variable happened to cause myStruct.sj to be 0, but there's no guarantee that this will be the case.

To initialize a variable, you have to give it a value at the time it is defined:

struct s myStuct = { 9 };

One you do this, then you'll see the contents of myStruct.sj set to 0. This is guaranteed as per section 6.7.8 of the C standard (with highlighting specific to this case):

10 If an object that has automatic storage duration is not
initialized explicitly, its value is indeterminate. If an object
that has static storage duration is not initialized
explicitly
, then:

—if it has pointer type, it is initialized to a null
pointer;

if it has arithmetic type, it is initialized to (positive or
unsigned) zero;

if it is an aggregate, every member is initialized
(recursively) according to these rules;

—if it is a union, the first
named member is initialized (recursively) according to these rules.

...

21 If there are fewer initializers in a brace-enclosed list than there
are elements or members of an aggregate
, or fewer characters in a
string literal used to initialize an array of known size than there
are elements in the array, the remainder of the aggregate
shall be initialized implicitly the same as objects that have static
storage duration.

How To Initialize a C Struct using a Struct Pointer and Designated Initialization

You can use a pointer to a compound literal:

struct NODE{
int x;
int y;
}


struct NODE *nodePtr = &(struct NODE) {
.x = 20,
.y = 10
};
  • Notice that compund literals were introduced in C99.


Related Topics



Leave a reply



Submit