Monday, May 19, 2003
Duh! After ten years of head-scratching, I finally know why K&R brace placement treats functions differently from other constructs. Consider:
Why is this not written like this?
Turns out that the only reason it was a mystery to me is because I never experienced the pre-ANSI-C days. My K&R is the second edition. Here's how this would've been written in, say, 1980:
Now, because that nasty little "int x;" has to go between the function and the brace, the function definition is already inconsistent with that nice clean for() loop. So you may as well place everything on its own line.
I was finally shown the light when I happened to run accross this (10-year-old!) article.
The new "opening brace at end of line, even for functions" style obviously came about after ANSI, when people noticed the "inconsistency". This is the style that got picked up by Java. (But, strangely, not in the C source of the JVM itself).
void foo(int x)
{
int i;
for(i=0;i<x;i++) {
printf("help!\n");
}
}
Why is this not written like this?
void foo() {
int i;
for(i=0;i<x;i++) {
printf("help!\n");
}
}
Turns out that the only reason it was a mystery to me is because I never experienced the pre-ANSI-C days. My K&R is the second edition. Here's how this would've been written in, say, 1980:
foo(x)
int x;
{
int i;
for(i=0;i<x;i++) {
printf("help!\n");
}
}
Now, because that nasty little "int x;" has to go between the function and the brace, the function definition is already inconsistent with that nice clean for() loop. So you may as well place everything on its own line.
I was finally shown the light when I happened to run accross this (10-year-old!) article.
The new "opening brace at end of line, even for functions" style obviously came about after ANSI, when people noticed the "inconsistency". This is the style that got picked up by Java. (But, strangely, not in the C source of the JVM itself).