Variables have three characteristics:
1. a type
2. a variable name, which is defined when the variable is declared,
e.g. int line_number;
3. a value, which is usually assigned to the variable with the = operator,
e.g. line_number = 1;
The variable may also be initialized (be given an initial value) on declaration,
e.g. int line_number = 1;
All variables must always be declared once (and only once) before they can be used in the program. As a rule, only data of the same type as the variable can be stored in it.
Arithmetic types are an exception in C++. C++ can automatically convert arithmetic types if it is possible. It is correct to say int i = 5.5; NOTE: round-off errors and overflow may occur. A compiler will also complain about such things, so don not do this at home!
After declaration a variable name in the program is substituted with the latest value given to it (with some exceptions as mentioned earlier). Variable declaration can be placed in two places in the program code:
- Inside any code block (between braces {}) where a statement could be placed. These are called local variables and can only be used inside the program segment it was declared in.
- Outside all program segments. These kinds of variables are global variables.
It is recommended not to use global variables.
The name of the variable must start with a letter A-Z, a-z. The rest of the characters can also be numbers or underscore '_' characters. However, it is a good programming practice to use meaningful variable names that suggest what they present.
e.g. int current_val = 10; vs int xyz = 12;
A variable can also be a constant. It behaves like any variable but its value cannot be changed. A constant is declared in the same way as a variable but a reserved word const is places before hte declaration. For example:
const int TEMPERATURE = 10;
Constants must always be initialized on declaration since the value cannot be changed after declaration.
When declaring a variable, always think hard what kind of data it represents. The type of the data determines the type of the variable.
A data value with a type and a value but without a name is called a literal. Literals can also be called unnamed constants. For example:
'x', 123456, 3.1415, "Help" are all literals.
No comments:
Post a Comment