36

我以为我对 C 语法非常了解,直到我尝试编译以下代码:

void f(int i; double x)
{
}

我预计编译器会跳闸,它确实发生了,但我没有收到错误消息:

test.c:1:14: error: parameter ‘i’ has just a forward declaration

然后我尝试了

void fun(int i; i)
{
}

失败了

test.c:1:17: error: expected declaration specifiers or ‘...’ before ‘i’

最后

void fun(int i; int i)
{
}

令我惊讶的是,它成功了!

我从未在现实世界的 C 代码中见过这种语法。它的用途是什么?

4

2 回答 2

33

这种形式的函数定义:

void fun(int i; int i)
{
}

使用称为参数前向声明功能的 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) {}  

在 OP 示例中,

void fun(int i; int i) {}

前向参数声明没有任何用途,因为它没有在任何实际参数中使用,并且fun函数定义实际上等效于:

void fun(int i) {}

请注意,这是一个 GNU C 扩展,它不是 C。编译gcc-std=c99 -pedantic会给出预期的诊断:

警告:ISO C 禁止前向参数声明 [-pedantic]

于 2013-07-21T10:46:06.810 回答
-1

这取决于您使用的是哪个编译器。不带“;”试试 并使用“,”。

于 2019-06-30T06:26:19.687 回答