1

These two arrays have the same size and elements:

  int list[] = {1,2,5,2,5,2,5,2,};
  //                           ^ extra comma 
  int size1 = sizeof(list)/sizeof(list[0]);
  
  int list2[] = {1,2,5,2,5,2,5,2};
  int size2 = sizeof(list2)/sizeof(list2[0]);

  std::cout << "size1: " << size1 << " size2: " << size2 << "\n"; // size1: 8 size2: 8
  • So, are they completely the same ?

Why is that extra comma allowed? I get it can be practical whe you copy-paste arrays like

someComplicatedStruct list3[] = 
{ {1,5,3},
  {1,2,9},
  {1,2,6},
  {7,2,3},
//       ^ Is this actually usefull?
};

But it seems risky, if it is, why is this allowed?

Ivan
  • 1,352
  • 2
  • 13
  • 31
  • What would be the risK? – YSC Mar 31 '21 at 09:37
  • 2
    Check out [this question and answer](https://stackoverflow.com/questions/7043372/int-a-1-2-weird-comma-allowed-any-particular-reason) .. long story short, a.) it's part of the standard and allowed by the language, and b.) it makes it slightly easier to add/remove hard-coded array elements. – txtechhelp Mar 31 '21 at 09:40
  • @YSC like, I could imagine a warning telling you "Hey, did you forget to add an element?" – Ivan Mar 31 '21 at 09:40
  • Thanks @txtechhelp I'm checking it – Ivan Mar 31 '21 at 09:41
  • 1
    the reason is the same in other languages: [Trailing commas and C++](https://stackoverflow.com/q/6372650/995714), [Why is a trailing comma in a function call not a syntax error?](https://stackoverflow.com/q/53672206/995714), [Why are trailing commas allowed in a list?](https://stackoverflow.com/q/11597901/995714), [Why does C# allow trailing comma in collection initializers but not in params?](https://stackoverflow.com/q/26865030/995714) – phuclv Mar 31 '21 at 09:42
  • It is basically to maintain uniformity. That you are treating all lines as the same. – Suyash Krishna Mar 31 '21 at 09:45
  • A warning is not a risk. What would be the risk to have that comma? – YSC Mar 31 '21 at 09:48
  • @YSC I mean , the risk of forgetting an element – Ivan Mar 31 '21 at 10:11
  • Putting the comma but forgetting the last element is a pretty uncommon case compared to forgetting both. – YSC Mar 31 '21 at 10:21

0 Answers0