I would like to know what happens when there are more initializers than array size, e.g. :
int t[3] = { 1, 2, 3, 4 };
Of course, my compiler warns it. I expected undefined behavior, but I didn't find any clause about it in C11 standard. So, did I miss something ?
The code is ill-formed in both C and C++.
C++11 §8.5.1[dcl.init.aggr]/6 states:
An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of members or elements to initialize.
C11 §6.7.9/2 states:
No initializer shall attempt to provide a value for an object not contained within the entity being initialized.
I took a look at the assembler gcc generated for your example, and it looks like it takes the "safe" route; it simply doesn't load values past the size of the array:
void main() {
int t[3] = { 1, 2, 3, 4 };
}
Generates the following assembly:
main:
pushl %ebp
movl %esp, %ebp
subl $16, %esp
movl $1, -12(%ebp)
movl $2, -8(%ebp)
movl $3, -4(%ebp)
leave
ret
This was generated with gcc 4.4.3.
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