-1

I noticed a piece of code that made me raise a few eyebrows in the code base which I am working on. Since I am not an expert of the C language, I first tried googling initializing fixed size arrays. However, I could not find anything like that:

float array[7] = {0.0,};

To be precise, I would like to know how the comma is interpreted in C here? I doubt it is a typing error, because I find this kind of initialization all over the place and for all types of arrays.

Is there any difference to just writing:

float array[7] = {0.0};
SuperTasche
  • 479
  • 1
  • 7
  • 17
  • 3
    both snippets behave the same; the comma after the last value (whether it fills the array) is optional. – pmg Mar 04 '21 at 12:53
  • 1
    Does this answer your question? [Array initialization C](https://stackoverflow.com/questions/16414622/array-initialization-c) – Pedro Mar 04 '21 at 13:30
  • duplicate: [C : Is this array initialization legal?](https://stackoverflow.com/q/23466831/995714), [`int a[] = {1,2,};` Weird comma allowed. Any particular reason?](https://stackoverflow.com/q/7043372/995714). See also [Trailing commas](https://stackoverflow.com/q/6372650/995714), [Is the last comma in C enum required?](https://stackoverflow.com/q/792753/995714) – phuclv Mar 04 '21 at 14:52

1 Answers1

1

This has nothing to do with floats. It goes for all arrays. Imagine that that rule did not exist and you you have this:

float arr[] = {
    4.5, 
    2.3,
    3.8
};

Later, you realize that you want to remove 3.8. Then you would ALSO need to remove the comma after 2.3. And the same thing goes if you want to insert a new value. Let's say that you have copied a value from somewhere. Now you cannot simply paste it. Because if the copied string has a comma, you could not simply paste it anywhere you want in the array.

The basic purpose is that you should not have to think about adding and removing commas. It's just convenience.

Imagine copying and pasting regular code and you would have to think about that for the semicolon everytime. That would be a bit annoying. That's how it is in Pascal. ;)

klutt
  • 30,332
  • 17
  • 55
  • 95