Variables

 

Just as in C, there are different types of variables defined with some specific keywords. Variables are defined as 'a data item that may take on more than one value during the run time of a program'. Variable has to be of a specified data type.

 

int: Stores all kinds of integers e.g. 12, 873

double: Stores floating point numbers which are decimals e.g. 12.3, 16.1
char: Stores single letters, or we can say characters of a string e.g. 'G', 'g'

string: Collection of characters makes a string. These are written in double quotes e.g."Demo Code"
bool: Stored values are either true or false. Shorthand for 'Boolean'.

 

How to declare a Variable?

Just as in C, we need to mention it's data type followed by the variable and equate it to it's value. However assigning a value to the variable is not necessary.

Syntax:

type variable= value; 

 

 

Example:

double num=5;

 

Note: The value of the variable can be overwritten by declaring the variable again later in the code. In order to make the value of variable fixed and avoid over-writting's possibility the const keyword is used.

 

const int num=5; // num will always be 5 and it's value will not change. If it is overwritten later in the code this will show an error.

 

C++ Identifiers

Identifiers are the names of functions, variables, structures etc. (the elements we define) used to identify them.

All c++ identifiers must be identified with unique names.

Examples include x,y as well as age, num etc.


 

Note: Using informative identifiers such as num, age are suggested to increase readability of code.

Rules for constructing identifier names:

1) Can consist of letters, digits and underscores

2) Must begin with a letter or an underscore

3) These are case sensitive

4) Whitespaces or special characters like !, #, %, etc. Are not allowed

5) Reserved words such as int or cout cannot be used as names