Thursday, December 10, 2015

C++ and aggregate initialization

There is an easier way to initialize a char array with all 0s instead of using the traditional memset

So this code

char array1[1024];
memset(array1, 0, sizeof(array1));

can be replaced with

char array[1024] = {0};
char array[1024] = {}; //same as {0}

Which is basically the same but on a single line implementation.

Section 8.5.1 of the ISO Spec states

"An aggregate is an array or a class with  no user declared constructors, no private or protected non static data members, no base classes, and no virtual functions"

If you want to initialize such an aggregate you can use {}.

This is not only  used to set everything to 0, but to also initialize class members.

For e.g.

struct ExampleStruct
{
   int x;
   int y;
   int z;
};

If you have a simple struct like this with no constructors, all public members, then you can initialize its members in a single line like this

ExampleStruct Object = { 2, 3, 6 };

Which would set x = 2, y = 3 and z = 6.

Also as per C++11, = {0} is required to set the padding bytes to 0 by the standards. For e.g

struct ExampleStruct
{
   char x;
   int y;
}

ExampleStruct Object = {0}
will set x = 0 and y = 0 , and the padded bytes between x and y will be 0.



No comments: