What is the significance of comma in array and structure initialization? [duplicate]

北城以北 提交于 2019-12-12 19:26:11

问题


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.


回答1:


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.

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

See this python script that generates such code:

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

It is simple. Now try writing a code without trailing comma. It wouldn't be that simple.

The standard also allows trailing-comma in enum definition:

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

Hope that helps.



来源:https://stackoverflow.com/questions/18160469/what-is-the-significance-of-comma-in-array-and-structure-initialization

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