What's the rationale for preventing assignment to arrays?

后端 未结 6 433
抹茶落季
抹茶落季 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:30

    The answer is simple: It never was allowed before the committee got involved (even struct-assignment was considered too heavy), and considering there's array-decay, allowing it would have all kinds of interesting consequences.

    Let's see what would change:

    int a[3], b[3], *c = b, *d = b;
    a = b; // Currently error, would assign elements
    a = c; // Currently error, might assign array of 3?
    c = a; // Currently pointer assignment with array decay
    c = d; // Currently pointer assignemnt
    

    So, allowing array-assignment would make (up to) two currently disallowed assignments valid.

    That's not the trouble though, it's that near-identical expressions would have wildly different results.

    That gets especially piquant if you consider that array-notation in function arguments is currently just a different notation for pointers.
    If array assignment was introduced, that would become even more confusing.
    Not that enough people aren't completely confounded by things as they are today...

    int g(int* x);  // Function receiving pointer to int and returning int
    int f(int x[3]);// Currently the same. What afterwards? Change to value-copy?
    

提交回复
热议问题