Array Assignment

前端 未结 3 1405
心在旅途
心在旅途 2020-12-19 14:47

Let me explain with an example -

#include 

void foo( int a[2], int b[2] ) // I understand that, compiler doesn\'t bother about the
                  


        
3条回答
  •  独厮守ぢ
    2020-12-19 15:10

    The answer is in the concept "pass by value", which means that the called function receives copies of the arguments -- which are pointers to ints. So a and b are local copies of those pointers (which don't exist in the caller; they were the results of conversions from the arrays, that is, the addresses of their first elements). It would be no different if you wrote

    void foo( int aparam[2], int bparam[2] )
    {
        int* a = aparam;
        int* b = bparam;
    
        a = b ;
    }
    

    Dennis Ritchie has acknowledged that the array syntax for parameters is a wart on the language, and was only there to ease conversion of B programs -- ancient history! It also had a deleterious effect on the design of C++, because arrays cannot be passed by value. This syntax is a constant source of confusion. So ... don't use it; pretend it's not legal. If everyone does that, it can fade away and maybe in a few decades can be given proper semantics.

    Update: For more information on call-by-value (the only form of call in C and Java; see my comments below), call-by-reference (added in C++), and other evaluation strategies, see http://en.wikipedia.org/wiki/Evaluation_strategy

提交回复
热议问题