当非const参数作为const参数传递时,Intel C ++编译器警告167

时间:2013-02-15 18:35:15

标签: c compiler-warnings icc

我有一个很大的代码库,最近从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的相同条款,但我认为问题非常不同。

2 个答案:

答案 0 :(得分:2)

将变量传递给需要const的函数时,将变量转换为const。

foo( (const int (*)[2]) stuff );

Why can't I pass a char ** to a function which expects a const char **?

Similar question

答案 1 :(得分:2)

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元素。

相关问题