什么是逗号的阵列和结构初始化的意义何在? [英] What is the significance of comma in array and structure initialization?

查看:126
本文介绍了什么是逗号的阵列和结构初始化的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然通过一些codeS浏览,我遇到这种初始化方法:

While browsing through some codes, i came across this method of initialization:

#include<stdio.h>

struct trial{
    int x, y;
};

int main(){
    int a[10] = {0,1, };//comma here
    struct trial z = {1, };//comma here
    return 0;
}

这是什么逗号运算的意义是什么?如果逗号运算符被删除我不觉得在初始化的方法有什么区别。

What is the significance of this comma operator? I do not find any difference in the method of initialization if the comma operator is removed.

推荐答案

这是有道理的,如果你生成脚本,code。它使你的脚本简单。没有边缘的情况。特别是,你不打扰你是否需要添加一个第一,写多了一个项目之前;你只写一个项目接着一个逗号,你就大功告成了!

It makes sense if you generate such code from scripts. It keeps your script simple. No edge-cases. In particular, you don't bother whether you need to add a , first, before writing one more item; you just write one item followed by a comma and you're done!

您不关心的第一项或最后一项。所有项目的相同的,如果有一个结尾逗号。

You don't care about the first item or last item. All items are same if there is a trailing comma.

但从code代点思考。这将开始制作感。

Think from code-generation point of view. It would start making sense.

请参阅产生此种code这个python脚本:

See this python script that generates such code:

print ("int a[] = {")
for item in items:
    print (item + ",")
print ("};")

这很简单。现在试着写一个code没有尾随逗号。它不会是的的简单。

该标准还允许尾随逗号枚举定义:

The standard also allows trailing-comma in enum definition:

enum A
{
    X,
    Y,
    Z, //last item : comman is okay
};

希望有所帮助。

这篇关于什么是逗号的阵列和结构初始化的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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