Array index out of bound in C

后端 未结 10 1123
抹茶落季
抹茶落季 2020-11-21 21:58

Why does C differentiates in case of array index out of bound

#include 
int main()
{
    int a[10];
    a[3]=4;
    a[11]=3;//doe         


        
10条回答
  •  -上瘾入骨i
    2020-11-21 22:46

    As litb mentioned, some compilers can detect some out-of-bounds array accesses at compile time. But bounds checking at compile time won't catch everything:

    int a[10];
    int i = some_complicated_function();
    printf("%d\n", a[i]);
    

    To detect this, runtime checks would have to be used, and they're avoided in C because of their performance impact. Even with knowledge of a's array size at compile time, i.e. sizeof(a), it can't protect against that without inserting a runtime check.

提交回复
热议问题