is a sequence of letters, digits and underscores; but must not start with a digit.
Identifiers are
. myInt, MyInt, and myINT are 3 different identifiers!
There are several
that are reserved, they will be listed later on.
Variables
Variables are used to store any value you want, hence the name.
A variable must have a specific
data type, or
type, so the compiler knows how much memory to use and how to store values.
Common data types are
int for integers,
char for characters and
double for floating-point real numbers.
When
declaring a variable, first comes the type, then a unique name you choose that best suits the value that will be stored there, followed by the semicolon to end the statement:
int foo;
char myInitial;
double money;
Multiple declarations of the same type can be placed in the same statement by separating each name with a comma:
int foo, bar;
char b, c, d;
A variable can be assigned a value using the
assignment operator which is
=.
If a variable is assigned a value when it's declared, it's said to be
initialized to that value.
Take a look at this code:
int foo = 3;
double money, pi = 3.14;
int bar = 8, goal;
goal = 21;
In this example, foo, pi and bar are initialized. Then goal is assigned the value of 21.
Constants
Constants are values that must be determined at compile-time, that is, the value is only set before the program runs and cannot change. By convention, constant names contain letters that are all upper case:
const int SECRET_NUMBER = 4;
Now, SECRET_NUMBER can be used in each place that you want your secret number, such as:
int topSecret = SECRET_NUMBER;
topSecret is a variable of type int that is initialized with SECRET_NUMBER, which is 4.
This method is preferred because if the initial secret number ever needed to be changed, all you need to do is change that const declaration in one spot and all places that use SECRET_NUMBER are automatically updated.