2011年3月23日 星期三

C++ two coding styles for value initialization

There are two coding styles for value initialization:
• T t = {};
• T t = {0};

The result are the same for most situations, but there are still some differences.
My conclusion in summary is to use {} instead of {0} for ordinary situations because all members in struct or array will be initialized with same logic.


Struct

Typedef struct _A
{
int x;
std::string y;
Float z;
} A;

A a; // the value of A is not initialized and will be arbitrary value
A a = {0}; // A.x will be set to 0. y and z will be set the default value, which is empty string and 0
A a = {}; // a.x as well as y and z will be set to default value (0 for x and z, empty string for y)
A a = {2}; // A.x will be 2, y will be empty string and z will be 0

In this situation, the results of {} and {0} are the same.

However, if

typedef struct _B
{
std::string x;
int y;
} B;

B b = {0}; // GPF, because 0 is set to x
B b = {}; // x will be empty string and y will be 0

Array

char a[100]; // not initialized and all elements are arbitrary value
char a[100] = {0}; // all of the 100 elements are 0
char a[100] = {}; // all of the 100 elements are 0
char a[100] = {2}; // a[0] is 2, and the other 99 elements are 0

so the result of char a[100] = {0}; and char[100] = {}; are the same.

沒有留言:

wibiya widget