Question

I am passing a bool array to function and doing some modifications in the passed array inside the function, the changes that I do in the function are reflected in the original array that I passed to the function.For example ,in the code below the output is 1 .Why am I getting this output ? When we pass an integer variable for example ,the local variable maintains its local value .How can I retain local copy of the original bool array locally in the code below.

#include<iostream>
using namespace std;
void fun(bool A[30])
{
    A[0]=true;
}
int main()
{
    bool used[3];
    used[0]=used[1]=used[2]=0;
    fun(used);
    cout<<used[0];
}
Was it helpful?

Solution

Why am I getting this output ?

when passing array "by value" the array itself is not being copied, only a copy of the pointer to its address is passed to the callee (placed on the stack). Regardless of whether you declare the parameter as bool[] or bool*, it decays into a pointer. So you can still modify the contents of the array from within the called function.

How can I retain local copy of the original bool array locally?

you can use std::array or you can workaround this by wrapping the array in a struct or class, because the default copy operator will copy the array:

struct Array_by_val
{
  bool my_array[30];
};

void func (Array_by_val x) {}

int main() {
   Array_by_val x;
   func(x);
}

Quoting 6.3.2.1p3 in the C99 standard:

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

The same paragraph in the C11 standard is essentially the same, with the addition of the new _Alignof operator.

see here:

Why can't arrays be passed as function arguments?

OTHER TIPS

When you pass an array to a function, in fact you pass the pointer to the first element. That's why the changes that you do to the array in the function are reflected in the original array. You cannot pass an array by value. This is because:

Copying arrays would be kind of complicated and not very clear, since the behavior would change for different parameters and different function declarations.

Why can't we pass arrays to function by value?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top