Home > Back-end >  Difference between int x = 5; and int x = {5}
Difference between int x = 5; and int x = {5}

Time:03-16

Both of these statements work the same:

int x = 5;
int x = {5};

That's also true when I try:

char str[] = "hello";
char str[] = {"hello"};

How does the language define initializing a variable using curly braces?

CodePudding user response:

There is no difference. In the C11 standard, §6.7.9p11 describes this case:

The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

Both the integer and the pointer are scalar types (see §6.2.5p21).

(It is the same in C89, the document is just not as nice to link to).

CodePudding user response:

There are three different cases of initialization which apply here:

  • For plain variables/pointers, formally called scalars, then C17 6.7.9 §11 says that you can optionally add braces if you like:

    The initializer for a scalar shall be a single expression, optionally enclosed in braces.

  • Then §14 mentions character arrays specifically - they may be initialized with a string literal. And again they may optionally have braces:

    An array of character type may be initialized by a character string literal or UTF–8 string literal, optionally enclosed in braces.

  • Finally, §16 deals with all other initializers of aggregates (arrays or struct) and unions, braces are no longer optional but mandatory:

    Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed list of initializers for the elements or named members.

This makes it possible to write all initializer lists with consistent syntax and using {} no matter which type that the initializer list is initializing. Which in turn can perhaps be handy when writing type-generic macros and similar.

  • Related