What's the rationale for preventing assignment to arrays?

后端 未结 6 426
抹茶落季
抹茶落季 2020-12-18 17:57

I\'ve tried to google this and have read:

  • Why can\'t arrays of same type and size be assigned?
  • Assigning arrays
  • Assign to array in struct in
6条回答
  •  轮回少年
    2020-12-18 18:26

    The reason is basically historic. There was a C even before ISO C89 which was called "K&R" C, after Kernighan and Ritchie. The language was designed to be small enough so a compiler would fit in severely limited (by today's standards) memory of 64kb.

    This language did not allow assigning arrays. If you wanted to copy same-sized arrays, memcpy was there for your needs. Writing memcpy(a, b, sizeof a) instead of a = b is certainly not a big complication. It has the additional advantage of being generalizable to different-sized arrays and array slices.

    Interestingly, the struct assignment workaround you mention also did not work in K&R C. You had to either assign members one by one or, again, use memcpy. The first edition of K&R's The C Programming language mentions struct assignment as a feature for future implementation in the language. Which eventually happened with C89.

提交回复
热议问题