In C++, a variable is a name given to a memory location that represents the basic unit of storage in a program.
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;
// Declaring multiple variables:type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore ‘_’ character. However, the name must not start with a number.
Initialization of a variable in C++
In the above diagram,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable
float simpleInterest;
// Declaring integer variable
int time, speed;
// Declaring character variable
char var;
We can also provide values while declaring the variables as given below:
int a=50,b=100; //declaring 2 variable of integer type
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type
int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED
The variable declaration refers to the part where a variable is first declared or introduced before its first use. A variable definition is a part where the variable is assigned a memory location and a value. Most of the time, variable declaration and definition are done together.
See the following C++ program for better clarification:
// C++ program to show difference between
// declaration and definition of a
// variable
#include <iostream>
using namespace std;
int main()
{
// Declaration of an integer variable
int x;
// Initialization of the integer variable 'x'
x = 15;
// Definition of the integer variable 'y'
int y = 20;
// Declaration and definition of a character variable 'ch'
char ch = 'Z';
// Definition of a floating-point variable 'f'
float f = 3.14;
// Multiple declarations and definitions
int a, b, c;
// Printing the value of the variable 'ch'
cout << "The value of the character variable ch is: " << ch << endl;
return 0;
}
There are three types of variables based on the scope of variables in C++
Types of Variables in C++
Variables are essential components of any programming language, and C++ is no exception. In C++, there are three types of variables - Local Variables, Instance Variables, and Static Variables. Let's take a look at each of these types in detail:
class Example
{
static int a; // static variable
int b; // instance variable
}
70 videos|45 docs|15 tests
|
|
Explore Courses for Software Development exam
|