-2

Why does int arr[2]={10,20,30,40,50} leads to error? Why can't this initialization escape error by Array Bound Checking?

int arr[2] ;
arr[0]=10, arr[1]=20, arr[3]=30, arr[4]=40;

Doesn't cause error in context to C language by array bound checking?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • The keyword is "undefined behaviour". You should have read about it in your C book, if not re-read it or get a better book. For details, so some basics research, there is a plethora of posts about this already. – too honest for this site Sep 10 '17 at 19:06
  • @T.Akki what is the reason of abusing the contract between you and the compiler? You say 2 elements bu later assign the 30rth. What for? Better think how to avoid it in your programs. – 0___________ Sep 10 '17 at 19:11
  • A compiler is only required to inform you what cannot be compiled, not what cannot be run, although they do have various helpfulness. – Weather Vane Sep 10 '17 at 19:24
  • @PeterJ_01 Isn't the 2nd example abusing the contract between me and the compiler ? – noobwithskills Sep 10 '17 at 19:36

1 Answers1

1

There is no runtime array bounds check in C. You are free to obliterate whatever is in memory. The 1st example you show, is a compile-time structure, so the compiler know that you declared an array of size 2, and that the initialization has > 2 elements.

OldProgrammer
  • 12,050
  • 4
  • 24
  • 45