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.
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
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With