Initializing an array and structure in C ++

I would like to initialize some structure and array elements in C ++.

In C you can:

unsigned char array[30] = {[1] = 4, [20] = 4}; struct mystruct { int i; int j; } struct mystruct e = {.j = 2}; 

But I can not do it in C ++. Is there a way to implement such designated initializers?

+4
source share
2 answers

In C++ struct has constructors (just like class ), so you can always initialize them with var.

+1
source

It is always useful to initialize ALL elements in an array or structure to avoid many errors.

Below can help you.

Initialization for the structure

 struct myStruct { int i; int j; myStruct() { j=10; //default Constructor } }; 

Initialization for an array:

 unsigned char array[5]; array[0]='A'; array[2]='C'; 
0
source

All Articles