Initialize array in c in the format `int a[3]={0,};` [duplicate]
Asked Answered
B

1

2

I had seen a source where array initialize in int arr[3] ={0,}; What does it mean ? I normally use this format int arr[3]={0}; can i know what is the difference

Byrom answered 20/7, 2016 at 3:38 Comment(0)
M
5

This is probably a dup, but I'll take a shot anyhow.

There is no difference between int arr[3] ={0,}; and int arr[3] ={0};.

Ref: C11 6.7.9:

    initializer:
         assignment-expression
         { initializer-list }
         { initializer-list , }

Both forms of initializer lists are considered initializers. The form with the comma at the end is preferred by many because it makes it easier to rearrange or add elements to the list during code maintenance.

 int arr[3] ={0,}; 

declares an array of three elements and initializes the first element to 0. When you do a partial initialization, the rest of the array is automatically initialized with zeros.

Ref. C11 6.7.9:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Monogram answered 20/7, 2016 at 4:15 Comment(2)
The question is a complete duplicate of Array initialization C. That said, I like your answer better than the ones given there.Surgeonfish
The dup mentioned in the answer SO 7043372 is a C++ question, whereas this is for C. It's preferable to keep C questions duplicated to other C questions.Milano

© 2022 - 2024 — McMap. All rights reserved.