Recently I've been looking at the some of the C example code from the online resources of Steven Skiena's "Algorithm Design Manual" and have been baffl开发者_如何学JAVAed by the syntax of some of his function calls. Admittedly it's been a while since did C at uni but I've never encountered untyped function arguments like this:
find_path(start,end,parents)
int start;
int end;
int parents[];
{
if ((start == end) || (end == -1))
printf("\n%d",start);
else {
find_path(starts,parents[end],parents);
printf(" %d",end);
}
}
Is this valid syntax anymore? Are / were there any benefits with this style of function declaration? It seems more verbose than the conventional inline typing of arguments.
They are called K&R style definitions. Don't use them in new code. Even K and R recommend that you stay away from them in "The C Programming Language 2ed".
A note of history: the biggest change between ANSI C and earlier versions is how functions are declared and defined.
The parameters are named between the parentheses, and their types are declared before opening the left brace; undeclared parameters are taken as
int
.The new syntax of function prototypes makes it much easier for a compiler to detect errors in the number of arguments or their types. The old style of declaration and definition still works in ANSI C, at least for a transition period, but we strongly recommend that you use the new form when you have a compiler that supports it.
This is an old style way of giving the function types. It was dropped in the C99 standard and is not appropriate for modern code.
The arguments are typed, just not inline. The types are between the first line and the opening bracket.
Anyway, this style is old and not recommended.
These K&R definitions are the historically traditional way to define functions. In the original C this was the only way to define a function.
Don't use K&R definitions any more. Why not? Because doing so stops the compiler being able to check for type mismatches.
This old syntax stems from the typeless B programming language (and as others stated, is not in standard C anymore):
printn(n,b) {
extrn putchar;
auto a;
if(a=n/b) /* assignment, not test for equality */
printn(a, b); /* recursive */
putchar(n%b + '0');
}
By the way, some compilers may offer a flag that let you compile this oldstyle K+R code.
精彩评论