Is a C ++ array passed by reference or pointer?

At school, our lecturer taught us that the entire array was passed by reference when we pass its functions.

However, I recently read a book. He says that arrays are passed by default pointer when passing the entire array to a function. The book goes on to say that “following a pointer is very similar to passing by reference,” which means that passing by pointer and passing by reference is really different.

It seems that the other source is different in different ways.

So my question is: In C ++, are arrays passed by reference or by pointer when we pass the entire array to a function?

Example:

void funcA(int []); //Function Declaration

int main()
{
    int array[5];
    funcA(array); //Is array passed by ref or by pointer here?
}
+4
3

. . , , . , ; "" , " ", " ".

, - C, , .

:

void funcA(int[]);

:

void funcA(int*);

:

funcA(myArray);

:

funcA(&myArray[0]);

; .

, /, " ", " " " ", ++, .

+10

, , . ,

void funcA(int []);

int[] - int*. , funcA , int*.

. , , :

int array[42];  // array is of type int[42]
int * arr = array; // array decays to int*

, array funcA,

funcA(array); // array decays to int*

funcA .

. .

void funcB(int (&arr)[42]);

, - funcA. funcB(array), .

+2

. ++. . , , .

: .

:

void foo(int *arr);
void bar(int *&arr);
void baz(int * const &arr);
void quux(int (&arr)[42]);

, :

  • foo (arr) , .
  • bar (arr) , () , . , , , , , ( ). , (MSV++) . , (, int *p = arr; bar(p);)
  • baz (arr) , (const).
  • quux (arr) .

What your book means with their help is that passing a pointer by value and passing a reference are usually implemented the same way. The difference lies only in the C ++ level: with a link, you do not have a pointer value (and therefore cannot change it), and it is guaranteed to refer to the actual object (if you have not violated your program before).

+1
source

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


All Articles