将非const参数传递给需要const参数的函数时出现警告。有没有更好的办法? [英] Warning when passing non-const parameter to a function that expects const parameter. Is there a better way?

查看:598
本文介绍了将非const参数传递给需要const参数的函数时出现警告。有没有更好的办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个参数传递给一个函数,并且指出参数应该被接收函数视为 const

I am trying to pass a parameter to a function, and indicate that the parameter should be considered const by the receiving function.

我的理解是,下面的代码示例显示了确保 test 函数可以用 argv调用的唯一方法变量,它没有声明为const。

It was my understanding that the following code example shows the only way to ensure that the test function can be called with the argv variable, which is not declared as const.

void test(const char * const *arr);

int main(int argc, char *argv[], char *env[])
{
    test(argv);
}

void test(const char * const *arr)
{
}

然而,gcc给了我一个警告,如下所示:

However, gcc gives me a warning such as the following:

E:\Projects\test>gcc -o test test.c
test.c: In function 'main':
test.c:5:2: warning: passing argument 1 of 'test' from incompatible pointer type
[enabled by default]
test.c:1:6: note: expected 'const char * const*' but argument is of type 'char **'

这让我相信我在这里所做的是某种错误。
是否有更好的方法将参数传递给一个函数,并指出它应该被接收函数视为 const

This leads me to believe that what I am doing here is somehow wrong. Is there a better way to pass a parameter to a function, and indicate that it should be considered const by the receiving function?

推荐答案

C FAQ a>解释了为什么在C中将指针转换为非 const 为 const 时存在安全警戒。在你的情况下,如果有一个双重的 const 合格的目标指针,那么在那里描述的问题就不会发生,我想。所以C ++有一个宽松的规则,允许你所要求的隐式转换。不幸的是,对于C来说,标准委员会发现C ++的规则太复杂了,所以你必须将指针转换为预期类型。

The C FAQ explains why in C there is a safe guard when converting a pointers to non-constto const. In your case of a doubly const qualified target pointer the problem that is described there wouldn't occur, I think. So C++ has a relaxed rule that would allow the implicit conversion that you are asking for. Unfortunately for C the standards committee found the rule from C++ too complicated, so you'd have to cast your pointer to the expected type.

这篇关于将非const参数传递给需要const参数的函数时出现警告。有没有更好的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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