5

I downloaded a piece of C code and it uses this style of defining functions:

int somefunction(name1, name2) 
int name1;
int name2;
{
    // do stuff, using name1 and name2
}

Why or when would you use this syntax, and what difference does it make with the more well known syntax where parameter types are inside the parentheses?

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • See e.g. [this old question](http://stackoverflow.com/q/3092006/440558). – Some programmer dude Oct 01 '14 at 14:17
  • I think [How is the ANSI C function declaration an improvement on the old Kernighan and Ritchie style?](http://stackoverflow.com/questions/14243959/) is a good question to reference — and maybe the one to make this a duplicate of. There may also be earlier questions about this notation. – Jonathan Leffler Oct 01 '14 at 14:32

1 Answers1

9

That is the very old, pre-standard C syntax for defining functions — also known as K&R notation after Kernighan and Ritchie who wrote "The C Programming Language" book. It was allowed by C89/C90 of necessity — the standard added the new prototype form of function declaration, but existing code did not use it (because back in 1989, many compilers did not support and very little code had been written to use it). You should only find the notation in code that has either not been modified in over twenty years or that still has claims to need to support a pre-standard compiler (such claims being dubious at best).

Do not use it! If you see it, update it (carefully).

Note that you could also have written any of:

somefunction(name1, name2) 
{
    // do stuff, using name1 and name2
}

int somefunction(name1, name2) 
int name2;
int name1;
{
    // do stuff, using name1 and name2
}

int somefunction(name1, name2) 
int name1;
{
    // do stuff, using name1 and name2
}

and doubtless other variants too. If a return type was omitted, int was assumed. If a parameter type was omitted, int was assumed. The type specifications between the close parenthesis and open brace did not have to be in the same order as the parameter names in the parenthesized list; the order in the list controlled the order of the parameters.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Thanks. The code is indeed old (1998), but works fine and compiles without warnings with gcc 3.3.2. – Bart Friederichs Oct 01 '14 at 14:40
  • It'll compile with GCC 4.9.1 without warnings if you don't elicit them and use C89 mode (which is still the default). I suggest that the code should be upgraded, because that form of definition is obsolescent (deprecated) and will be removed from the standard at some time, but it will de facto be safe for a decade or two yet. – Jonathan Leffler Oct 01 '14 at 14:44