claws
claws

Reputation: 54100

This is a valid C code but not a valid C++ code?

In some library I'm using (written in C) its

StorePGM(image, width, height, filename)
char *image;
int width, height;
char *filename;
{
  // something something
}

All functions are defined this way. I never seen such function definitions in my life. They seem to be valid to MSVC but when I compile it as C++ it gives errors.

What is it? some kind of old version C?

Upvotes: 10

Views: 1092

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263177

Before the 1989 ANSI C standard, C didn't have prototypes (function declarations that specify the types of the parameters); these old-style declarations and definitions were all that was available.

In 1989, the ANSI C standard (which essentially became the 1990 ISO C standard) introduced prototypes. If I recall correctly, the idea actually came from C++ (which had not yet been standardized at the time). Old-style declarations and definitions remained legal, so that old code could still be compiled. The 1989 standard also said that old-style declarations were "obsolescent", meaning that they could be removed in a future version of the standard.

The 1999 ISO C standard, which (officially) superseded the 1990 standard, left this alone; old-style declarations and definitions are still legal, and all conforming compilers must support them (though they're free to warn about them, as they can warn about anything else).

As of the latest C201X draft (large PDF), this still hasn't changed. Old-style function declarations and definitions are still a required part of the language, and all conforming compilers must support them. (Personally, I consider this unfortunate.)

C++, on the other hand, has never (?) supported anything other than prototypes as function declarations; Stroustrup wasn't as concerned about maintaining compatibility with old C code.

But unless you need to maintain very old code and/or use very old compilers, there is no good reason to use old-style function declarations or definitions.

Note that, at least in C, this definition:

int main() {
    /* ... */
}

is actually an old-style definition. It's correct for C++, where it's a prototype indicating that main has no parameters, but in C it should be

int main(void) {
    /* ... */
}

(C++ also accepts this form for compatibility with C -- but by the time you're writing main, you should already have decided which language you're using.)

Upvotes: 5

MartinStettner
MartinStettner

Reputation: 29164

Yep, it's K&R-Style. (Kernighan & Ritchie are the inventors of C) See also http://www.lysator.liu.se/c/bwk-tutor.html for examples of this pre-ANSI style.

Upvotes: 0

Alex Budovski
Alex Budovski

Reputation: 18436

Yes. K&R, pre-standard C. Avoid using it.

Upvotes: 16

Related Questions