Array assignment

Let me explain with an example -

#include <iostream> void foo( int a[2], int b[2] ) // I understand that, compiler doesn't bother about the // array index and converts them to int *a, int *b { a = b ; // At this point, how ever assignment operation is valid. } int main() { int a[] = { 1,2 }; int b[] = { 3,4 }; foo( a, b ); a = b; // Why is this invalid here. return 0; } 

This is because the array decays to a pointer when passing the function foo(..) , the assignment operation is possible. And in main , this is because they are of type int[] , which invalidates the assignment operation. Does a,b in both cases mean the same thing? Thanks.

Change 1:

When I do this in the foo function, it sets the location of the starting element b's to a . So, thinking in terms of this, what caused the language developers not to do the same in main() . Want to know the reason.

+4
source share
3 answers

You answered your question.

Because these

 int a[] = { 1,2 }; int b[] = { 3,4 }; 

are of type int[2] . But these

 void foo( int a[2], int b[2] ) 

are of type int* .

You can copy pointers, but you cannot copy arrays.

+9
source

The answer lies in the concept of "pass by value", which means that the called function receives copies of the arguments, which are pointers to int. Thus, a and b are local copies of these pointers (which do not exist in the caller, they were the result of conversions from arrays, that is, the addresses of their first elements). It would not be otherwise if you wrote

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

Dennis Ritchie admitted that the array syntax for the parameters is a wart in the language, and he was only there to facilitate the conversion of B programs - ancient history! It also had a detrimental effect on C ++ design, since arrays cannot be passed by value. This syntax is a constant source of confusion. So ... do not use it ; pretend it's not legal. If everyone does this, he can disappear, and maybe in a few decades he will be given proper semantics.

Refresh . For more information about calling by value (the only form of calling 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

+1
source

In the main function
a and b are constant pointers, in fact they are the addresses of the first elements. They are similar to l-value. you cannot copy the value of l, but you can change the value of the integers that they point to.

In foo function
a and b are pointers. therefore you can change their values.

-2
source

Source: https://habr.com/ru/post/1343383/


All Articles