Variables in C++
In C++, a variable is a named memory location that stores a value of a specific data type. A variable can be thought of as a container that holds a value. The value stored in a variable can change during the execution of a program. Variables play an important role in C++ programming as they allow you to store, manipulate, and access data in your programs.
To use a variable in C++, you must first declare it by specifying its name and data type. For example:
int a;
a=25;
The first statement declares a variable and the second statement assigns a value of 25 to it.
You can also make declarations and assignments in a single statement. It will look like
int a=25;
Rules for declaring a variable
The following are the rules for declaring a variable in C++:
Variable names must start with an alphabet
Variable names in C++ are case-sensitive, so “age” and “AGE” are considered to be two different variables.
Variable names cannot be reserved words or keywords, such as “int” or “for”.
Each variable must have a unique name within the same scope.
A variable must be declared with a specific data type, such as int, float, double, etc. This determines the size and range of values that can be stored in the variable.
A sample C++ program that illustrates the use of variables in C++
#include <iostream.h>
#include <math.h>
#include <conio.h>
void main()
{
int a=25;
float b=23.6;
double age=9.5;
clrscr();
cout<<"Value of integer variable"<<a<<endl;
cout<<"Value of float variable"<<b<<endl;
cout<<"Value of double variable"<<age<<endl;
getch();
}