C++ Variables

Variables in C++ can be used to store data in the memory location and whose value can be changed during the program execution.

C++ variables

In C++ variables are case sensitive. They can be represented using letters, digits, and underscore.

Rules for Declaring variables in C++

If you want to declare any variables in C++, we just need to follow some rules. They are as follows:

  • The first character must be a letter (or) underscore.
  • Blank spaces cannot be used in variable names.
  • A variable name consists of uppercase, lower case, numbers.
  • Special characters like #, $  are not allowed.
  • C++ keywords cannot be used as names.
  • And all the names are case sensitive.
  • The variable name consists of 31 characters only if we declare the variable more than one character, the compiler will ignore after 31 characters.
  • variable types can be bool, char, int, float, double, void, wchar_1.

C++ Variables Example:

#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f; 
int main () {
//Variable definition:
int a, b;
int c;
float f;
//actual initialization
a = 10;
b = 20;
c = a + b; 
cout<<c<<endl ;
f=70.0/3.0;
cout << f << endl ;
return 0;
}

Output:

30
23.3333

Variable Definition in C++

A variable definition in C++ is nothing but it defines when a programmer writes some instructions to tell the compiler to create the storage in the memory location.

Syntax: data_type variable_name;

Here data_type means it includes int, float, double, char, wchar_t, bool.

Example:

int    width,height,age;/*variable definition*/
char   letter;
float  area;
double d;

Variable Declaration in C++

Variable initialization in C++ is nothing but the variable values can be assigned and the initial values can be assigned along with their declaration.

Syntax: data_type variable_name = value;

Example:

int width,height=5,age=32;/*variable definition and initialization*/
char letter='A';
float area;
double d;
/*actual initialization*/
width = 10;
area = 26.5;