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: