Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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 middle of a function in C as in C++?

like image 794
koool Avatar asked Aug 27 '11 23:08

koool


1 Answers

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.

like image 58
osgx Avatar answered Sep 22 '22 05:09

osgx