3

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

8
  • 1
    what does getFirstEven() return when arr has only odd values? Commented Dec 17, 2017 at 23:07
  • That's not the error I get here: ideone.com/HhK87h Commented Dec 17, 2017 at 23:07
  • Unrelated: I hope your array contains an even number or else weirdness will bite you. Commented Dec 17, 2017 at 23:07
  • 1
    I don't get your warning with clang++. Which compiler do you use? Commented Dec 17, 2017 at 23:07
  • I did not get that error message. I got the error message that getFirstEven may reach the end of a non-void function without a return. Commented Dec 17, 2017 at 23:07

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the answer. So for any functions that doesn't modify the data pointed by the pointer passed in, I have to declare "const" before the pointer, right? If I don't do this, does this cause any problems?
The const gives benefits and warning is that you may miss those. With const you can pass both pointers to const and to not const data to it and also the const documents your intention not to modify the data.
I agree with your answer, only it does not explain why the other function does not get the warning. arr is being used read only too in the other function. Why would that be?
@AlexisWilke I do not know. Perhaps capability of that tool to analyze the code of first function is limited by something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.