Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables between parentheses and curly braces [duplicate]

Tags:

c

syntax

function

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?

like image 569
Bart Friederichs Avatar asked Feb 11 '23 21:02

Bart Friederichs


1 Answers

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.

like image 163
Jonathan Leffler Avatar answered Feb 14 '23 10:02

Jonathan Leffler