A variable is a location in computer memory where you can store and retrieve a value . Variables are used for storing data during program execution and the values may be modified by the program. All variables must be declared before they can be used.
To declare (create) a variable you start with the data type you want the variable to hold followed by an identifier, which is the name of the variable.
Let's see the syntax to declare a variable:
type variable_list;
variable_list may consist of one or more identifier names separated by commas.
The example of declaring variable is given below:
int a; float b; char c;
Here, a, b, c are variables and int, float, char are data types.
To assign a value to a declared variable the equal sign is used, which is called the assignment operator (=).
The declaration and assignment can be combined into a single statement
type variable_name = value;
int x=5,b=10; //declaring 2 variable of integer type float f=30.8; char c='A'; int myInt = 50;
When the variable is declared there is an alternative way of assigning, or initializing the variable by enclosing the value in parentheses. This is known as constructor initialization and is equivalent to the statement above.
int myAlt (50);
If you need to create more than one variable of the same type there is a shorthand way of doing it using the comma operator (,).
int x = 1, y = 2, z;
std::cout
int a; int _ab; int a30;
iint 32Int; // incorrect (starts with number) int Int 32; // incorrect (contains space) int Int@32; // incorrect (contains special character) int new; // incorrect (reserved keyword)
The scope of a variable refers to the region of code within which it is possible to use that variable. Variables in C++ may be declared both globally and locally.
A global variable is declared outside of any code blocks and is accessible from anywhere after it has been declared. A global variable will remain allocated for the duration of the program.
int globalVar; // global variable
The default values for global variables are automatically initialized to zero by the compiler.
int globalVar; // initialized to 0
int main() { int localVar; } // local variable
The default values for local variables are not initialized at all. Uninitialized local variables will therefore contain whatever garbage is already present in that memory location.
int main() { int localVar; // uninitialized }
Using uninitialized variables is a common programming mistake that can produce unexpected results. It is therefore a good idea to always give your local variables an initial value when they are declared.
int main() { int localVar = 0; // initialized to 0 }