Louis Tran
Louis Tran

Reputation: 1156

C++ warning: "Pointer parameter "arr" can be pointer to const"

I have three functions below, I'm not sure why the second and the third one have a warning at *arr but the first one doesn't. What does the warning mean and how to fix this?

IDE: Clion 2017.3 MinGW64 5.0, CMake 3.9.4

Thank you.

int getFirstEven(int n, int *arr) {
    for (int i = 0; i < n; ++i) {
        if (arr[i] % 2 == 0)
            return arr[i];
    }
    return -1;
}

int getLastOdd(int n, int *arr) {
    int lastOdd = -1;
    for (int i = 0; i < n; ++i) {
        if (arr[i] % 2 != 0)
            lastOdd = arr[i];
    }
    return lastOdd;
}

int countElement(int n, int *arr, int e) {
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == e)
            cnt++;
    }
    return cnt;
}

enter image description here

Upvotes: 3

Views: 6619

Answers (1)

&#214;&#246; Tiib
&#214;&#246; Tiib

Reputation: 10979

It makes sense to favor immutability where possible and to indicate immutable things with const.

The warning means that your function does not modify the data pointed at by arr and so the function could be better declared with pointer to const parameter. About like that:

int getFirstEven(int n, int const* arr) {
    for (int i = 0; i < n; ++i) {
        if (arr[i] % 2 == 0)
            return arr[i];
    }
    return -1;
}

Upvotes: 6

Related Questions