Home > C++ > Variables in C++

In C++ Variables can be considered as memory location. They provide us a named storage that our program can manipulate.
Basic syntax

Declaration

Datatype variable_name;
Datatype: could be any one of the predefined or user defined data types discussed above.
variable_name: is the any valid name of the variable we created by following different rules for naming a c++ variable.

E.g.

     int x;       // can hold an Integer value
     float y;     // can hold a Floating point value
     char c;     // can hold a single character value
     bool b;     // can hold a Boolean value
     string s;   // can hold a string value

Initialization

Datatype variable_name = value;

Datatype: could be any one of the predefined or user defined data types discussed above.
variable_name: is the any valid name of the variable we created by following different rules for naming a c++ variable.
Value: – It is the value same as of datatype.
E.g.

     int x =10;
     float y =15.6; 
     char c ='a'; 
     bool b = true;
     string s = "Hello";

Rules for Naming Variables in c++: –

  1. Variable Name should not contain any space in it. Underscore ( _ ) can be used for this purpose
  2. No special character is allowed
  3. Name should start with an alphabet or underscore ( _ )
  4. Name should not be any keyword (Reserved) words from c++.

E.g.

     int x;       //Valid
     int 2x;      //Invalid
     int x_2;     //Valid
     float y 3;   //Invalid

Note: – C++ variable names are case sensitive.
i.e.

     int x;   
     int X;

Above two variables are different.

Scope of C++ Variables: –
Variables can be local or global.

Local: –
Local variables are the one which are not accessible outside the boundary in which they were created.
E.g. In the example below all the variables created inside main function are only accessible inside main function body.If we try
to access these variables outside main function, we will get a compile time error.


#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;
void main()
{
     int x = 10;
     int X = 20;
     float y = 15.6;
     char c = 'a';
     bool b = true;
     string s = "Hello";

     cout << s << endl<<x<<endl<<X<<endl<<y<<endl<<c<<endl<<b;
     getchar();<br>
}

Output:
local c++ Variables

Global: –
Global variables are the ones that are accessible everywhere in the program.
E.g. In the program written below X is a global variable and we can access it inside main function’s body as well.

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;
void main()
int X=20;
void main()
{
     int x = 10;
     float y = 15.6;
     char c = 'a';
     bool b = true;
     string s = "Hello";
     cout <<s<<endl<<x<<endl<<X<<endl<<y<<endl<<c<<endl<<b;
     getchar();
}


Output:
global c++ Variables

2 thoughts on “Variables in C++

Leave a Reply

Your email address will not be published. Required fields are marked *