Variable Declarations

Lines 9–11

int number1 = 0; // first integer to add (initialized to 0)
int number2 = 0; // second integer to add (initialized to 0)
int sum = 0; // sum of number1 and number2 (initialized to 0)

are declarations. The identifiers number1, number2 and sum are the names of variables. These declarations specify that the variables number1, number2 and sum are data of type int, meaning that these variables will hold integer values. The declarations also initialize each of these variables to 0.


Image Error-Prevention Tip 2.1

Although it’s not always necessary to initialize every variable explicitly, doing so will help you avoid many kinds of problems.


All variables must be declared with a name and a data type before they can be used in a program. Several variables of the same type may be declared in one declaration or in multiple declarations. We could have declared all three variables in one declaration by using a comma-separated list as follows:

int number1 = 0, number2 = 0, sum = 0;

This makes the program less readable and prevents us from providing comments that describe each variable’s purpose.


Image Good Programming Practice 2.3

Declare only one variable in each declaration and provide a comment that explains the variable’s purpose in the program.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.251.56