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

前端 未结 5 762
遥遥无期
遥遥无期 2021-02-09 14:18

I have a question, does anyone know why the variables have to be defined initialized at the beginning of a function? Why can\'t you initialize or define variables in the

相关标签:
5条回答
  • 2021-02-09 14:53

    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!

    0 讨论(0)
  • 2021-02-09 15:09

    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.

    0 讨论(0)
  • 2021-02-09 15:09

    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.

    0 讨论(0)
  • 2021-02-09 15:10

    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 讨论(0)
  • 2021-02-09 15:10

    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.

    0 讨论(0)
提交回复
热议问题