This question already has an answer here:
I have a large codebase that recently moved from Microsoft's compiler to the Intel C++ Compiler. Our team's goal is compilation without warnings in the mainline. Since the switch, one instance of warning 167 has confounded me. If I compile the following code:
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;
}
The ICC will give me warnings:
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);
Why should this be a warning? It is common practice to pass a non-const variable as a const parameter, and the types & dimensions are identical.
To those who have marked this a duplicate question, I urge you to reconsider. If someone else encounters this warning, they would have to know that in C arguments are converted as if by assignment in prototyped functions, and then search for a question that is strictly about assignment. Even though the answer ends up being the same clause from C90/C99, the question is, I think, pretty different.
Cast your variable as const when you pass it to the function that requires const.
foo( (const int (*)[2]) stuff );
Why can't I pass a char ** to a function which expects a const char **?
The value of stuff
array is of type int (*)[2]
.
int foo(const int pp_stuff[2][2])
is equivalent to
int foo(const int (*pp_stuff)[2])
In the function call, it is as if you were assigning a value of type int (*)[2]
to a variable of type const int (*)[2]
.
Arguments are converted as if by assignment in prototyped functions. And C let you assign two pointers if:
both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
Here int (*)[2]
and const int (*)[2]
are not qualified/unqualified versions of the same type. The qualifier applies to int
not to the pointer.
Use:
int foo(int (* const pp_stuff)[2])
if you want to make the pointer const
and not the int
elements.
来源:https://stackoverflow.com/questions/14901183/intel-c-compiler-warning-167-when-non-const-argument-is-passed-as-const-parame