10

Possible Duplicate:
C function syntax, parameter types declared after parameter list

I saw the following syntax for function definition in "Expert C Programming"

int compare(s1, s2)
    char * s1, *s2;
{
    while (*s1++ == *s2) {
        if (*s2++ == 0) return (0);
    }
    return (*--s1 - *s2);
}

How is the above definition valid? It compiles and runs perfectly without any errors.

I am more comfortable with the following syntax for function definition

int compare(char * s1,char *s2)
{
    while (*s1++ == *s2) {
        if (*s2++ == 0) return (0);
    }
    return (*--s1 - *s2);
}

and no where I've seen the one given in the book(While studying C in my college or elsewhere), can anyone please throw some light on the one given in the book.

Community
  • 1
  • 1
Kartik Anand
  • 4,513
  • 5
  • 41
  • 72
  • 5
    It's the old and deprecated syntax for function declarations. Sometimes called "K&R style". – cnicutar May 26 '12 at 14:02
  • 3
    It is an old style, but still accepted by the language. BTW: I don't think that an "expert C programming" book should contain `return (0);` – wildplasser May 26 '12 at 14:02
  • 20 years ago, compilers that couldn't handle the *second* syntax were quite common still. – Amadan May 26 '12 at 14:03
  • It does not hurt for the compiler to accept it. (it does not conflict with other syntax), so it would be a good choice to still accept it. – wildplasser May 26 '12 at 14:08
  • @peoro Sorry for that, but after confronting this syntax I wasn't sure whether it was a typo in the book or related to old style C – Kartik Anand May 26 '12 at 14:14
  • @peoro Actually I didn't even know that there exists a syntax for old K&R style C :) – Kartik Anand May 26 '12 at 14:16

2 Answers2

6

This topic has been discussed here before, it's the "Kernighan and Ritchie style" of function definition.

Nowadays you should prefer the second syntax, the first one is still accepted by some compilers for backwards compatibility reasons but it should be considered deprecated for all practical purposes.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    Thanks for the answer and sorry if some users think it is a duplicate..In my defence I never knew there exists a K&R style syntax for C, I've always seen ANSI C, even programs on the internet had syntax similar to ANSI C...So the first thing that came into my mind was a book typo and my question really was how can this still work.Thank you. – Kartik Anand May 26 '12 at 14:19
  • 1
    @Kartik No need to apologize! It appears that this question will be closed as a duplicate of that one, but that shouldn't be taken as an insult. It doesn't mean you asked a bad question or anything. It's OK to not know that K&R style existed; that's what we're here for! – Cody Gray - on strike May 26 '12 at 14:33
3

This is the pre-ANSI syntax, sometimes called the K&R C. It was the original syntax of C language.

cyco130
  • 4,654
  • 25
  • 34