Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the parameter types declared outside the parenthesis?

some times i see that functions are defined as below:

read_dir(dir)
char    *dir;   
{
        DIR * dirp;
        struct dirent *d;

        /* open directory */
        dirp = opendir(dir);
  ......... so  on

here what is the importance of the statement

char    *dir;

what is the intension behind declaring the pointer soon after the function name and then starting the function body.

like image 346
Vijay Avatar asked Apr 09 '10 12:04

Vijay


2 Answers

It's an older C syntax, kalled "K&R C" since it's how it appeared in the original version of the legendary book.

What used to be written like this:

foo(a, b)
int a;
int b;
{
}

is now

int foo(int a, int b)
{
}
like image 180
unwind Avatar answered Nov 18 '22 21:11

unwind


It is just "old style", K&R C function definition (see Kernighan & Ritchie's book, commonly referred to as simply Kernighan & Ritchie.)

The code you refer to may have been written in the late eighties, or early nineties with portability (i.e. compatibility with older compilers, possibly on more "exotic" platforms) in mind.

Even after the publication of the 1989 C standard, for many years K&R C was still considered the "lowest common denominator" to which C programmers restricted themselves when maximum portability was desired, since many older compilers were still in use, and because carefully written K&R C code can be legal Standard C as well.

Some people may believe that K&R-style function definition, still supported by compilers, are more readable, which is in fact not necessarily true; compare:

some_function(param1,param2,param3)
char    *param1;   /* param1 comment */
int     param2;    /* param2 comment */
short   param3;    /* param3 comment */
{
}

with

/* notice also that return type is explicitly specified now */
int
some_function(
  char    *param1, /* param1 comment */
  int     param2,  /* param2 comment */
  short   param3   /* param3 comment */
)   
{
}

K&R-style function definitions have been obsolete since 1989; see section 6.9.5 "Function definitions" in the C90 standard.

like image 22
vladr Avatar answered Nov 18 '22 20:11

vladr