2
int arr[5]={1,2,3,4,5,6,7,8,9};

This way of declaration is not giving an error and the array is stored up till the 4th index, if I try to output arr[5] it will give garbage value. Can anyone explain how this way is possible?

Edit: I was trying to run the following code in an online compiler:

#include <stdio.h>
int main() {
    int arr[5]={1,2,3,4,5,6,7,8,9};
    int i;
    for(int i=0; i<6;i++){
        printf("arr[%d]=%d\n", i,arr[i]);
    }
    return 0;
}
3
  • 7
    Buggy compiler? It requires a diagnostic. Commented Aug 24, 2021 at 12:33
  • 3
    You might tell us what compiler you are using. You should get some diagnostic message about providing excess elements in array initializer Commented Aug 24, 2021 at 12:33
  • 2
    It's possible because the compiler is not required to refuse it. Hmm, perhaps it is required to refuse it. Add -pedantic-errors if you're using gcc or clang, /permissive- if you are using MSVC. The program has undefined behavior anyway though. Commented Aug 24, 2021 at 12:33

1 Answer 1

6

It will initialize only 5 elements of the array. The remaining initializers will be ignored. The compiler will emit a diagnostic message (warning).

<source>:11:23: note: (near initialization for 'arr')
<source>:11:25: warning: excess elements in array initializer

This way of declaration is not giving an error and the array is stored up till the 4th index

This is correct - you need to read the warning messages and notes. Do not ignore warnings!!

if I try to output arr[5] it will give garbage value

You invoke Undefined Bahavour by reading outside the array bounds.

Sign up to request clarification or add additional context in comments.

2 Comments

The standard requires a diagnostic for a constraint violation.
@JonathanLeffler ammended

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.