3

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.

Nivetha
  • 698
  • 5
  • 17
  • 4
    This has been asked, and it's easier for tools to deal with or to add to later (see also enums). – chris Aug 10 '13 at 09:19

1 Answers1

4

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    Additionaly, allowing the comma at the last enum value is very handy if you #ifdef out some elements depending on configuration. If my memory serves, it became allowed in C with the 1999 standard. – Gauthier Sep 18 '14 at 08:23