开发者

Declaring variables before use in old C

Recently I had to modify a legacy code that was compiled with a very old version of GCC (somewhere around version 2.3). Within a function, varia开发者_如何学编程ble had to be declared before being used. I believe this is done C89 standard. This limitation is later removed.

My question is: Back then, why did they enforce this ruling? Was there any concern that could jeopardise the integrity of the software?


Variables still have to be declared before being used -- and they've never had to be declared just at the top of a function.

The C89 requirement is that a block consists of an opening {, followed by zero or more declarations, followed by zero or more statements, followed by the closing }.

For example, this is legal C89 (and, without the void, even K&R C, going back to 1978 or earlier):

int foo(void) {
    int outer = 10;
    {
         int inner = 20;
         printf("outer = %d, inner = %d\n", outer, inner);
    }
    printf("outer = %d, inner is not visible\n", outer);
    return 0;
}

C99 loosened this, allowing declarations and statements to be mixed within a block:

int foo(void) {
    int x = 10;
    printf("x = %d\n", x);
    int y = 20;
    printf("y = %d\n", y);
    return 0;
}

As for the reason for the original restriction, I think it goes back to C's ancestor languages: B, BCPL, and even Algol. It probably did make the compiler's job a bit easier. (I was thinking that it would make parsing easier, but I don't think it does; it still has to be able to distinguish whether something is a declaration or a statement without knowing in advance from the context.)


It was mainly to make compilers easier to write. If all the declarations were at the top of the function, it would be easy for the compiler to parse all the locals and determine how much stack is needed.

Of course now, compilers are a lot more mature than they were 30 years ago. So it makes sense to get rid of this restriction as it's become a nuisance to programmers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜