C ++警告:“指针参数" arr"可以是指向const的指针. [英] C++ warning: "Pointer parameter "arr" can be pointer to const"

查看:51
本文介绍了C ++警告:“指针参数" arr"可以是指向const的指针.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有三个功能,我不确定为什么第二个和第三个在* arr处有警告,而第一个没有.警告是什么意思,以及如何解决此问题?

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

IDE: Clion 2017.3 MinGW64 5.0, CMake 3.9.4

谢谢.

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;
}

推荐答案

在可能的情况下支持不可变性并使用 const 表示不可变性是有意义的.

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

警告表示您的函数不会修改 arr 所指向的数据,因此最好使用指向 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;
}

这篇关于C ++警告:“指针参数" arr"可以是指向const的指针.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆