Initialization of C array at time other than declaration?

前端 未结 5 487
[愿得一人]
[愿得一人] 2020-12-17 10:40

I know in C that I can do the following.

int test[5] = {1, 2, 3, 4, 5};

Now this is only legal when declaring the array. However I was wond

5条回答
  •  悲哀的现实
    2020-12-17 10:54

    The reason for that at the surface is that arrays are almost everywhere converted to a pointer to the first element. If you have two arrays

    double A[5];
    double B[5];
    

    in an expression such as

    A = B;
    

    both are already converted to pointers. The A on the left is in particular not an "lvalue" so you can't assign to it.

    This sounds like a lame excuse, but my guess is that historically it just happened like that. C (and C++ with it) was trapped in an early syntax choice and if you want to stay compatible with legacy code there is probably not much way out of it.

提交回复
热议问题