What is a parameter forward declaration?

Fred Foo picture Fred Foo · Jul 21, 2013 · Viewed 22.5k times · Source

I thought I knew C syntax quite well, until I tried to compile the following code:

void f(int i; double x)
{
}

I expected the compiler to trip, and it did, but I don't get the error message:

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

I then tried

void fun(int i; i)
{
}

which fails with

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

and finally

void fun(int i; int i)
{
}

which, much to my surprise, succeeds!

I've never seen this syntax in real-world C code. What is its use?

Answer

ouah picture ouah · Jul 21, 2013

This form of function definition:

void fun(int i; int i)
{
}

uses a GNU C extension called the parameter forward declaration feature.

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

This feature allows you to have parameter forward declarations before the actual list of parameters. This can be used for example for functions with variable length array parameters to declare a size parameter after the variable length array parameter.

For example:

// 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) {}  

In the OP example,

void fun(int i; int i) {}

the forward parameter declaration does not serve any purpose as it is not used in any of the actual parameters and the fun function definition is actually equivalent to:

void fun(int i) {}

Note this is a GNU C extension and it is not C. Compiling with gccand -std=c99 -pedantic would give the expected diagnostic:

warning: ISO C forbids forward parameter declarations [-pedantic]