char 数组声明中的字符串文字周围的大括号有效吗?(例如 char s[] = {“Hello World"}) [英] Braces around string literal in char array declaration valid? (e.g. char s[] = {"Hello World"})

查看:18
本文介绍了char 数组声明中的字符串文字周围的大括号有效吗?(例如 char s[] = {“Hello World"})的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

偶然我发现行 char s[] = {"Hello World"}; 被正确编译并且似乎被视为与 char s[] = "Hello世界";.不是第一个 ({"Hello World"}) 一个包含一个字符数组元素的数组,因此 s 的声明应为 char *s[]?事实上,如果我将其更改为 char *s[] = {"Hello World"}; 编译器也会按预期接受它.

By accident I found that the line char s[] = {"Hello World"}; is properly compiled and seems to be treated the same as char s[] = "Hello World";. Isn't the first ({"Hello World"}) an array containing one element that is an array of char, so the declaration for s should read char *s[]? In fact if I change it to char *s[] = {"Hello World"}; the compiler accepts it as well, as expected.

正在寻找答案,我找到的唯一提到这个的地方是 这个 但没有引用标准.

Searching for an answer, the only place I found which mentioned this is this one but there is no citing of the standard.

所以我的问题是,为什么行 char s[] = {"Hello World"}; 被编译,尽管左侧是 array of char 和右边是char数组的array?

So my question is, why the line char s[] = {"Hello World"}; is compiled although the left side is of type array of char and the right side is of type array of array of char?

以下是一个工作程序:

#include<stdio.h>
int main() {
    char s[] = {"Hello World"};
    printf("%s", s); // Same output if line above is char s[] = "Hello World";
    return 0;
}

感谢您的澄清.

附言我的编译器是 gcc-4.3.4.

P.S. My compiler is gcc-4.3.4.

推荐答案

这是允许的,因为标准是这样说的:C99 section 6.7.8, §14:

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.

这意味着两者

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

char s[] = "Hello World";

只不过是语法糖

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

在相关注释(同一部分,第 11 节)中,C 还允许在标量初始值设定项周围使用大括号,例如

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 }

这篇关于char 数组声明中的字符串文字周围的大括号有效吗?(例如 char s[] = {“Hello World"})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆