MohamedG's Log

TW9oYW1lZCBFbC1HZWlzaA==

Passing C++ Arrays by Value

Just in case you needed to, you can wrap an array into a struct/class and pass it by value to a function:

template<typename T, int N>
struct array {
    T value[N];
    T & operator[](int i) { return value[i]; }
};

template<typename T, int N>
void passByValue(array<T, N> a) {
    cout << “Value in function:” << endl;
    for (int i = 0; i < N; i++) a[i] = 1, cout << a[i] << endl; // prints 1’s
}

int main() {
    const int N = 5;
    array<int, N > a;

    for (int i = 0; i < N; i++) a[i] = 0;

    passByValue(a);

    cout << “Value after function call:” << endl;
    for (int i = 0; i < N; i++) cout << a[i] << endl; // prints 0’s

    return 0;
}