开发者

Does anyone know the reason why the variables have to be defined at the top of function

I have a question, does anyone know why the variables ha开发者_如何转开发ve to be defined initialized at the beginning of a function? Why can't you initialize or define variables in the middle of a function in C as in C++?


This is a tradition which comes from early C compilers, when compiler needs all local variable definitions before the actual code of function starts (to generate right stack pointer calculation). This was the only way of declaring local variables in early C language, both pre-standard (K&R) and first C standard, C90, published at 1989-1990 ( ANSI X3.159-1989, ISO/IEC 9899:1990 ).

C99 - the 1999 year ISO standard (ISO/IEC 9899:1999) of C allows declaraions in the middle of function.

C++ allows this because it is newer language than C. C++ standards are ISO/IEC 14882:1998 and ISO/IEC 14882:2003, so they are from 1998 and 2003 years.

You can initialize variable (give it a value: a=4;) at the definition point or any time later.


That is a left-over from early C. C99 allows variables to be defined anywhere in the function, including in loop structures.

for (int i = 0; i < 10; ++i) { int j; }

The throwback is from when compilers needed to know the size of the stack for the function before they instantiated the function's code. As compilers became better the requirement just became annoying.


You can do this in C so long as you use a C99 compiler. The restriction was lifted in C99.

Presumably the restriction was originally there because compilers were less capable, or perhaps simply because nobody thought of allowing such a convenience for the programmer.

When answering a question like this it is sometimes worth turning it around. Why would the original designers of C have done it the other way? They didn't have C++ to guide them!


In C++ and C99, you can define variables in the middle of a function. What you cannot do is refer to a variable that has not yet been defined.

From the point of view of object-oriented programming, it wouldn't make much sense otherwise: By defining a variable you bring an object to life (by calling its constructor). Before that, there is no object, so there's nothing to interact with until you pass the point of object construction.


Try writing a compiler with the primitive power of the old times and you'd realize flexibility is something you'd rather kill to get the software to work.

Putting variables first, then other statements simply made their parser/compiler code simpler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜