43

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?

2
  • What is your compiler? I guess it is either a bug or an extension (doesn't compile with clang 2.8). Commented Jul 21, 2013 at 10:45
  • @md5: GCC. Passes with -std=c99 too; I guess I should have tried CLang, which trips. Commented Jul 21, 2013 at 10:48

1 Answer 1

45

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]

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah! that ISO theory , +1 to you and I wish I could have done a +5 to OP for breaking the barriers try something unusual , at least for me :)
this feature was proposed to be integrated to C23, see open-std.org/jtc1/sc22/wg14/www/docs/n2780.pdf
However, it did not make it into C23.
If a semicolon is accidently used instead of a comma in the parmeter llist, this error message is provoked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.