In general, variable definitions or declarations can be placed anywhere within the program that a statement is allowed. A variablemust be declared or defined before it is used.
It is usually a good idea to define an object near the point at which the object is first used.
Defining an object where the object is first used improves readability. The reader does not have to go back to the beginning of a section of code to find the definition of a particular variable. Moreover, it is often easier to give the variable a useful initial value when the variable is defined close to where it is first used.
One constraint on placing declarations is that variables are accessible from the point of their definition until the end of the enclosing block. A variable must be defined in or before the outermost scope in which the variable will be used.
EXERCISES SECTION 2.3.6
Exercise 2.19: What is the value of j in the following program
- int i = 42;
- int main()