Braces around string literal in char array declaration valid? (e.g. char s[] = {“Hello World”})

拈花ヽ惹草 提交于 2019-11-27 13:51:13

It's allowed because the standard says so: C99 section 6.7.8, §14:

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

What this means is that both

char s[] = { "Hello World" };

and

char s[] = "Hello World";

are nothing more than syntactic sugar for

char s[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', 0 };

On a related note (same section, §11), C also allows braces around scalar initializers like

int foo = { 42 };

which, incidentally, fits nicely with the syntax for compound literals

(int){ 42 }
Nawaz

The braces are optional, and the expression is equivalent to just an array of char.

You can also write this:

 int a = {100}; //ok

Demo : http://ideone.com/z0psd

In fact, C++11 generalizes this very syntax, to initialize non-arrays as well as arrays, uniformly. So in C++11, you can have these:

int a{}; //a is initialized to zero, and it is NOT an array

int b[]{1,2,3,4}; //b is an array of size 4 containing elements 1,2,3,4

int c[10]{}; //all 10 elements are initialized to zero

int *d{}; //pointer initialized to nullptr

std::vector<int> v{1,2,3,4,5}; //vector is initialized uniformly as well.

Any variable in (int, char, etc.) is just an array of length 1.

char s = {0};

works as well.

I might be wrong, but I think this is not an array of arrays of chars, but a block contains an array of chars. int a = {1}; may work as well.

[...] In fact if I change it to char *s[] = {"Hello World"}; the compiler accepts it as well, as expected

The compiler accepets it,because actually, you're making an array 2D of undefined size elements,where you stored one element only,the "Hello World" string. Something like this:

char* s[] = {"Hello world", "foo", "baa" ...};

You can't omit the bracets in this case.

This is allowed by the C++ standard as well, Citation:

[dcl.init.string] §1

An array of narrow character type ([basic.fundamental]), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow string literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces ([lex.string]). [snip]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!