Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd C/C++ initialization syntax for integral type variable

Tags:

c++

c

compilation

The following snippet compiles perfectly with C/C++ compiler:

#include <stdio.h>
int main()
{
    int x = {5};         //<-- why this compiles?
    printf("x = %d",x);
    return 0;
}

The output is 5. x is initialized here in a compound-type form although it's of integral type. I would like to understand what conversions are made here and why.

like image 604
SomeWittyUsername Avatar asked Jul 05 '13 14:07

SomeWittyUsername


2 Answers

C allows it in:

(C99, 6.7.8p11) "The initializer for a scalar shall be a single expression, optionally enclosed in braces."

C++ has a similar rule in C++11, 8.5.4p1

like image 197
ouah Avatar answered Sep 30 '22 05:09

ouah


There is no convertions made here, it is standard defined way of variable initialisation.

8.5.4 List-initialization [dcl.init.list]

1 List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. List-initialization can occur in direct-initialization or copy- initialization contexts; list-initialization in a direct-initialization context is called direct-list-initialization and list-initialization in a copy-initialization context is called copy-list-initialization.
[Note: List-initialization can be used — as the initializer in a variable definition (8.5)
...
[ Example: int a = {1};

like image 33
alexrider Avatar answered Sep 30 '22 05:09

alexrider