Syntax of Variable Declaration
Recall that syntax means the grammar of a computer
language.
We can talk about the syntax of just a small part of a program,
such as the syntax of variable declaration.
There are several ways to declare a variable:
dataType variableName;
- The first way declares a variable, declares its data type,
and reserves memory for it.
It says nothing about what value is put in memory.
(Later in these notes you will learn that in some circumstances the variable is
automatically initialized, and that in other circumstances the variable is
left uninitialized.)
dataType variableName = initialValue ;
- The second way declares a variable, declares its data type,
reserves memory for it,
and puts an initial value into that memory.
The initial value must be of the correct dataType.
dataType variableNameOne, variableNameTwo ;
- The third way declares two variables, both of the same data type,
reserves memory for each, but puts nothing in any variable.
You can do this with more than two variables,
if you want.
dataType variableNameOne = initialValueOne,
variableNameTwo = initialValueTwo ;
- The fourth way declares two variables, both of the same data type,
reserves memory, and puts an initial value in each variable.
You can do this all on one line if there is room.
Again, you can do this for more than two as long as you follow the pattern.