- A variable is a data name given to a data value stored in the memory.
- The value of variable can vary at the time of execution.
- Name of the variable should be meaningful and in C++ there are some rules are defined for naming variables which are as follows:
Rules for naming variable
- Variable name may contain letters, digits and underscore (_) character.
- The variable name can begin with the letters as well as with underscore (_) character.
- A variable name should not start with digit.
- A variable name cannot contain punctuation characters like (@,#,$,%,^,&,* etc)
- A variable name cannot be a keyword.
- The variable names may be a combination of uppercase and lowercase characters. For example name and naME are not the same. Both are different.
Declaration of Variables
- We must declare the variable before using it into the program.
- A variable is declared using a data type and a meaningful variable name. The basic syntax of variable declaration is as follows:
- A variable can be of any data type like int, float, double and char etc.
- Here are some examples of variable declaration:
int a,b,c;/*More than one variable of same type can be declare in single statement.*/
- Variable can be initialized using the assignment operator '='.
- Variable declaration and initialization can also be performed in same line.
- The basic syntax to initialize a variable is as follows:
- Here is an example of variable initialization:
- Here is an example of using variable in C++ program:
int a;/*Variable declaration*/
cout<<"\nvalue of a is:"<<a;
- The output of the above program is as follows:
value of a is:5