·
We define a variable by stating
its type, followed by one or more spaces, followed by the variable name and a
semicolon. E.g.: bool IsOK
·
The variable name can be
virtually any combination of letters, but it cannot contain spaces.
·
Legal variable names include j,
i245abcd, and mySalary.
·
Good variable names tell us
what the variables are for; using good names makes it easier to understand the
flow of the program. The following statement defines an integer variable called
int mySalary:
·
Many programmers prefer to use
all lowercase letters for their variable names. If the name requires two words
(for example, my car), two popular conventions are used: MyCar, myCar. The
latter form is called camel notation because the capitalization looks something
like a camel’s hump with the former known as Pascal case.
·
Keywords Some words are
reserved by C++, and so they cannot be used as variable names. These keywords
have special meaning to the C++ compiler. Keywords include if, while, for, and
main. A list of Microsoft C++ keywords is available at:
NOTE: Since these series of tutorials in the playlist use Visual Studio 2017
for creating and running the C++ programs, hence the above is the relevant
comprehensive updated list.
·
More than one variable can be
created at a time as follows:
unsigned int myHeight, myWeight ; ( A ) // two unsigned int variables
long int width, length, area, parameter; ( B ) // four
long integers
Important: long is the
shortcut for using long int and short is the shortcut for using short int
NOTE: In A above, if the
word “unsigned” is not present then the output will accept it as “signed”
integer which can take both + and – values for the integers. However, if it is
unsigned, it is assumed to take only + values and -ve values may show garbage as
below:
·
Variables are assigned values
as follows: assign a value to a variable by using the assignment operator (=).
Thus, we would assign 8 to width by writing
unsigned short width; (or simply short width)
(VARIABLE DECLARATION)
width = 5; (VARIABLE ASSIGNMENT)
The declaration and
assignment can be combined in one line as:
short width = 5;
·
Just as we can define more than
one variable at a time, we can initialize more than one variable at creation.
For example, the following creates two variables of type long and initializes
them:
long width = 5,
length = 7;
·
This example creates three type
int variables, and it initializes the first (myAge) and third (hisAge):
int myAge = 39, yourAge,
hisAge = 40;