C++ is a strongly-typed language, and requires every variable to be declared with its type before its first use.
This informs the compiler the size to reserve in memory for the variable and how to interpret its value.
The syntax to declare a new variable in C++ is straightforward: we simply write the type followed by the variable name (i.e., its identifier).
char c; //character variable declaration.
int area; //integer variable declaration.
float num; //float variable declaration.
These are three valid declarations of variables.
char
with the identifier c
.int
with the identifier area
.float
with the identifier num
.Once declared, the variables c
, area
and num
can be used within the rest of their scope in the program.
If declaring more than one variable of the same type, they can all be declared in a single statement by separating their identifiers with commas.
int a, b, c; //more than one variable declaration.
This declares three variables (a
, b
and c
), all of them of type int
, and has exactly the same meaning as:
int a; //integer variable declaration.
int b; //integer variable declaration.
int c; //integer variable declaration.
When the variables in the example above are declared, they have an undetermined or garbage value until they are assigned a value for the first time. But it is possible for a variable to have a specific value from the moment it is declared. This is called the initialization of the variable.
In C++, there are same ways to initialize variables as in C Language.
type identifier = initial_value;
int a = 10; //integer variable declaration & initialization.
//Write a CPP program for declaration & initialization of variable
#include <iostream.h>
int main ()
{
int sum; //Variable declaration
int a = 10; //Variable declaration & initialization
int b = 5; //Variable declaration & initialization
ans = a + b;
cout << "Addition is:" << ans << endl;
return 0;
}
how to Declaration and Initialization of Variable in C++. related article
Ask Question