Fre*_*Foo 30 c parameters syntax forward-declaration
我以为我很熟悉C语法,直到我尝试编译以下代码:
void f(int i; double x)
{
}
Run Code Online (Sandbox Code Playgroud)
我期望编译器跳闸,但确实如此,但我没有收到错误消息:
test.c:1:14: error: parameter ‘i’ has just a forward declaration
Run Code Online (Sandbox Code Playgroud)
然后我试过了
void fun(int i; i)
{
}
Run Code Online (Sandbox Code Playgroud)
失败了
test.c:1:17: error: expected declaration specifiers or ‘...’ before ‘i’
Run Code Online (Sandbox Code Playgroud)
最后
void fun(int i; int i)
{
}
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,这成功了!
我从未在现实世界的C代码中看到过这种语法.有什么用?
oua*_*uah 29
这种形式的功能定义:
void fun(int i; int i)
{
}
Run Code Online (Sandbox Code Playgroud)
使用称为参数前向声明功能的GNU C扩展.
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
此功能允许您在实际参数列表之前具有参数转发声明.例如,这可用于具有可变长度数组参数的函数,以在可变长度数组参数之后声明大小参数.
例如:
// valid, len parameter is used after its declaration
void foo(int len, char data[len][len]) {}
// not valid, len parameter is used before its declaration
void foo(char data[len][len], int len) {}
// valid in GNU C, there is a forward declaration of len parameter
// Note: foo is also function with two parameters
void foo(int len; char data[len][len], int len) {}
Run Code Online (Sandbox Code Playgroud)
在OP示例中,
void fun(int i; int i) {}
Run Code Online (Sandbox Code Playgroud)
forward参数声明不起任何作用,因为它没有在任何实际参数中使用,并且fun
函数定义实际上等效于:
void fun(int i) {}
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个GNU C扩展,它不是C.使用gcc
并编译并-std=c99 -pedantic
提供预期的诊断:
警告:ISO C禁止转发参数声明[-pedantic]