C++ tutorial-C++ variables and datatypes

C++ variables and data types


A variable is what the program used to store a value in computer’s memory temporarily. The value stored in a memory location is cleaned when the program that uses it terminates.

Data type

Data types of variables tell the computer to store different types of values such as number, text, true/false, etc. They also inform the computer to reserve the different memory’s spaces for those variables. Here is a table of the data types of variables that can be used:




int Numeric – Integer -2 147 483 648 to 2 147 483 647
float Numeric – Real -3.4 * 1038 to 3.4 * 1038
double Numeric – Real -1.7 * 10308 to 1.7 * 10308
char Character All unicode characters
bool Boolean True or False

Declaring variables

In C++, before you can use a variable to store any value, it must be declared. To declare a variable in C++ you must write down its name immediately after its data type.

int a; //declare a variable named a to store an integer value

You can declare more than one variables of the same type on a single line by separating them with commas.


int i, j;  

Assigning values to variables

int i = 5;

char c='a';

bool b=true;

Alternativly, you can write as shown below.

int i;
char c;
bool b;

In C++, A variable can also be a signed variable or an unsigned variable. Signed means that it can have negative numbers and unsigned means it can't but unsigned gives a variable a greater positive range.


unsigned int i;

To give the variable a smaller or bigger range respectively, you need to put short or long keywords.
short int i;

String data type

A string is a type of variable that can store multiple words. You can declare a string in three ways. The first is to declare it as a string pointer by using  * symbol. The * means that it points to the first character of the string.


char *s;
s = "Hello";

The second way is to declare it as an array of characters which you must set a size when you declare it. You have to use the strcpy command to assign values to it. You must also include the string header file to be able to use the strcpy command.

char s[10];

The last way is to use the string data type.
string s="C++ programming";


Justin comment


this website helps as alot as a beginner

Harneet comment


Thankyou very much for this site. I even dont know a single word of c++. And now i m getting everything.

Troy comment


for more C++, C exercises,
please visit http://ccphplusplus.blogspot.com/


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.