Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialisation in C

Tags:

c++

arrays

c

I have doubt regarding the following piece of code :

int main()
{
    int array1 = {1,2,3,4,5}; //error in c++ , warning in c
    int array2[] = {1,2,3,4,5};
    int array3[5] = {1,2,3,4,5};
}

This piece of code gives a error on line 3 in c++ but not in c?

I know array1 is actually an int and array2 and array3 are arrays, so why doesn't a c compiler show a error , but just a warning: "excess elements in scalar initialization"

Is there a use of such a definition and why is it valid in c?

like image 911
voltaa7 Avatar asked Oct 29 '14 10:10

voltaa7


2 Answers

It is not valid C. See C11 6.7.9:

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

I would guess that you are using gcc. Then if you want your program to behave as strict standard C, compile it as such:

gcc -std=c11 -pedantic-errors

gives

error: excess elements in scalar initializer

like image 159
Lundin Avatar answered Sep 24 '22 05:09

Lundin


It isn't valid in C. It just has less checks on the code. This is Undefined behaviour.

From: C11 draft N1570; 6.7.9 Initialisation

Constraints
2 No initializer shall attempt to provide a value for an object not contained within the entity being initialized.
3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

Definitely breaks constraint 2. Is an int a complete object type?

from Annex J.2 (undefined behaviour):

The initializer for a scalar is neither a single expression nor a single expression enclosed in braces (6.7.9).

extra:
@James Kanze:

prog.c:4:12: error: expected identifier or ‘(’ before numeric constant
  int i = 1,2,3,4,5;
            ^

you can do it, but you need to make it one expression:

int i = (1,2,3,4,5); //need parenthesis, evaluates to 5, values 1-4 thrown away.

Compiling with an int initialised with an initalizer-list spawns a warning (in gcc):

prog.c:5:2: warning: excess elements in scalar initializer [enabled by default]
  int j = {1,2,3,4,5};
  ^

but it appears that the compiler is smart enough to only initialise the int and not the following memory. demo

like image 31
Baldrickk Avatar answered Sep 25 '22 05:09

Baldrickk