0

I have the following question: Lets say I have some function f of type int. So when I call this function f(a) the first thing that happens is that a new variable inside the function is declared int x=a; This is why if a have a function void f(int a){a++} calling that function for a certain variable wont change its value.

Now lets say a have a function of type int array[5]. What happens when I call this function? The reason I ask is because I read that it wont work if the function tries to initialize some other array with a.

Another thing I am wondering is the following. Would the arrays int a[5] and int b[6] be considered as having different data types?

Paul R
  • 208,748
  • 37
  • 389
  • 560
fibo11235
  • 153
  • 6

3 Answers3

5

void f(int a[5]) is misleading as it is in fact void f(int a[]) or void f(int *a).

To pass the size, you have to pass array by pointer or reference: void f(int (&a)[5])

So void f(int a[5]) and void f(int b[6]) are the same declaration of function.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

There is actually no semantic analogue for passing an array to a function (by value) as you would pass an integer. This is because array types are not allowed as a function argument.

There is a syntactic analogue: You can indeed write void(int[5]) but the meaning is different. This syntax actually means the same as void(int*). In other words, the argument is a pointer.


Another thing I am wondering is the following. Would the arrays int a[5] and int b[6] be considered as having different data types?

int[5] and int[6] are different types, yes. However, in a declaration of a function argument, the meaning of the syntax int[5] is not the type int[5] but int*. Likewise, the syntax int[6] also has the meaning of type int*. As such, in a declaration of a function argument and only in that context, int[5] and int[6] indeed mean the same type: int*.


An expression of an array type (int[C]) is automatically converted to pointer to first element (which has type int*) when passed as an argument. This conversion is called array decaying. Therefore, following well-formed:

void foo(int[5]); // type of argument is int*

void bar() {
    int arr[6];  // type of arr is not int*
    foo(arr);    // arr decays to int*
}

The array is not copied. Array to pointer conversion is performed, and that pointer is copied as the argument. As such, it is possible to modify the objects pointed by the pointer.

eerorika
  • 232,697
  • 12
  • 197
  • 326
-1

The value will be changed, because the reference of the array is sent instead of creating a new primitive type variable, like int x=0, and func(x);

When sending an array, the value (if changed within a function) will also change globally, because it changes the value of the reference pointer.

Farhan Qasim
  • 990
  • 5
  • 18