当非const参数作为const参数传递时,Intel C ++ Compiler警告167
我有一个很大的代码库,最近从Microsoft的编译器转移到了英特尔C ++编译器。 我们团队的目标是在主线上编辑而不发出警告。 自开关以来,警告167的一个实例让我感到困惑。 如果我编译以下代码:
int foo(const int pp_stuff[2][2]) { return 0; } int foo2(const int pp_stuff[][2]) { return 0; } int main(void) { int stuff[2][2] = {{1,2},{3,4}}; foo(stuff); foo2(stuff); return 0; }
国际刑事法院会给我警告:
1>main.c(17): warning #167: argument of type "int (*)[2]" is incompatible with parameter of type "const int (*)[2]" 1> foo(stuff); 1> ^ 1> 1>main.c(18): warning #167: argument of type "int (*)[2]" is incompatible with parameter of type "const int (*)[2]" 1> foo2(stuff);
为什么这是一个警告? 通常的做法是将非const变量作为const参数传递,并且类型和尺寸是相同的。
对于那些标有重复问题的人,我恳请你重新考虑。 如果其他人遇到此警告,他们必须知道在C参数中转换就像在原型函数中通过赋值一样转换,然后搜索严格关于赋值的问题。 尽管答案最终是C90 / C99中的同一条款,但我认为问题非常不同。
将变量传递给需要const的函数时,将变量转换为const。
foo( (const int (*)[2]) stuff );
为什么我不能将char **传递给期望const char **的函数?
类似的问题
stuff
数组的值是int (*)[2]
。
int foo(const int pp_stuff[2][2])
相当于
int foo(const int (*pp_stuff)[2])
在函数调用中,就像将int (*)[2]
类型的值赋给const int (*)[2]
类型的变量一样。
参数的转换就像在原型函数中赋值一样。 如果出现以下情况,C允许您分配两个指针:
两个操作数都是指向兼容类型的限定或非限定版本的指针,左边指向的类型具有右边指向的所有类型的限定符;
这里int (*)[2]
和const int (*)[2]
不是相同类型的限定/非限定版本。 限定符适用于int
而不是指针。
使用:
int foo(int (* const pp_stuff)[2])
如果你想使指针const
而不是int
元素。