【发布时间】:2015-09-30 11:54:51
【问题描述】:
我正在尝试使用 const 强制转换调用带有 const 矩阵参数的 c 函数,但找不到阻止 gcc 编译器抱怨的语法。如果删除了所有“const”强制转换,下面的代码编译时不会抱怨。该问题类似于C function const multidimensional-array argument strange warning,但没有提供完全令人满意的解决方案。在下面的代码中,如果第一次调用 g() 有效,那么第二次调用 g() 应该 也有效,因为它在语法上是相同的。但事实并非如此。首选 g() 的第二个版本,因为它不需要事先知道矩阵的类型。
/* file t.c */
void f(const int a[2]) {/*empty*/}
void g(const int b[2][2]) {/*empty*/}
int main()
{
int a[2];
int b[2][2];
f((const int (*)) a); /* ok */
f((const typeof(&a[0])) a); /* ok */
g((const int (*)[2]) b); /* ok */
g((const typeof(&b[0])) b); /* compiler complains */
}
$ gcc -o t t.c
t.c: In function ‘main’:
t.c:13:2: warning: passing argument 1 of ‘g’ from incompatible pointer type [enabled by default]
g((const typeof(&b[0])) b); /* compiler complains */
^
t.c:3:10: note: expected ‘const int (*)[2]’ but argument is of type ‘int (*)[2]’
void g(const int b[2][2]) {/*empty*/}
【问题讨论】:
-
const typeof(&b[0])是int (* const)[2],而不是const int (*)[2],即指针本身是 const,而不是元素。 -
演员没有做任何有用的事情。您可以将函数调用为
f(a)和g(b)。 -
是的,只要调用函数 f(a) 和 g(b),一切正常。问题只是编译器在抱怨。我有一个大代码,它使用 const 参数调用库函数。 gcc 在汇编中乱扔不应该存在的投诉。
标签: c matrix casting constants