The following C program creates an array which has fixed number of elements. Even when we assign three more value which exceeding the number of maximum array elements works fine.
#include <stdio.h>
int main(){
//declares a fixed sized array
int balance[5];
//initializing
balance[0] = 1;
balance[1] = 2;
balance[2] = 3;
balance[3] = 4;
balance[4] = 5;
//three more
balance[5] = 6;
balance[6] = 7;
balance[7] = 8;
printf("%d \n", balance[0]);
printf("%d \n", balance[1]);
printf("%d \n", balance[2]);
printf("%d \n", balance[3]);
printf("%d \n", balance[4]);
printf("%d \n", balance[5]);
printf("%d \n", balance[7]);
//and it works fine!
return 0;
}
But when we try to assign more than three element it throws an exception
#include <stdio.h>
int main(){
//declares a fixed sized array
int balance[5];
//initializing
balance[0] = 1;
balance[1] = 2;
balance[2] = 3;
balance[3] = 4;
balance[4] = 5;
//three more
balance[5] = 6;
balance[6] = 7;
balance[7] = 8;
//one more again
balance[8] = 9;
printf("%d \n", balance[0]);
printf("%d \n", balance[1]);
printf("%d \n", balance[2]);
printf("%d \n", balance[3]);
printf("%d \n", balance[4]);
printf("%d \n", balance[5]);
printf("%d \n", balance[7]);
printf("%d \n", balance[8]);
//throws an exception!
return 0;
}
But after declaring and initializing an array by using integer literals we can insert more elements without getting an error.
#include <stdio.h>
int main(){
//declares and initialize a fixed sized array
int balance[5] = {1,2,3,4,5};
//let's add few more
balance[5] = 6;
balance[6] = 7;
//and even more
balance[7] = 8;
balance[8] = 9;
balance[9] = 10;
printf("%d \n", balance[0]);
printf("%d \n", balance[1]);
printf("%d \n", balance[2]);
printf("%d \n", balance[3]);
printf("%d \n", balance[4]);
printf("%d \n", balance[5]);
printf("%d \n", balance[6]);
printf("%d \n", balance[7]);
printf("%d \n", balance[8]);
printf("%d \n", balance[9]);
//and it works fine!
return 0;
}
What is the reason for this behavior of C language?





a[5]and beyond are undefined behaviour, which is not a guarantee for failure. Stop trying to probe how far you can go and learn to spot and avoid such cases.