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
?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With