问题
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