Overview of Variables
Variables are containers which are used to store data values. The type of data a variable is storing is the data type of the variable.
Scope
- Local Variables - declared inside the function.
- Global Variables - declared outside the function.
Initializing a Variable
Rules for assigning names to variables
Names of variables are called identifiers. Use descriptive names for your variables to make your code readable.
- Length of name should be from 1 to 255 characters.
- Always start with letter or underscore.
- No space is allowed in the name of the variable.
- Contains only letters, underscores and numbers.
- Should not be a reserved keyword.
Note: While naming variables, keep in mind that C++ is a case sensitive language.
You can also declare variable without assigning value and assign value later, like;
You can also change the value of variable later in your code.
Another Example
Operations on variables
You can apply any mathematical operation on variables, but condition is that the data types of these variables must be compatible. You can not add int type variable to string. You can only add those variables whose data types are compatible.
Other types of variables
Like integer there are other different datatypes of variables.
- Int stores numbers without decimal like 10, 20, 3000.
- Float and double stores numbers with decimal like 2.1, 30.12 etc. The difference is that precision of double in 2x than float.
- Char stores single character
- String stores text (collection of characters) inside double quotes like, "My age is 20".
- Boolean stores true or false.
- Void is used when you do not want to assign any type to variable.
You can declare variables of the same type in one line, like:
Constant Variables
As name indicates, variable means “changeable”, but using const keyword you can make your variable unchangeable.
Printing different types of Variables
Styles for naming Variables
- Camel Case: In camel case convention, we start with small letter and if there are more than one words, we convert first letter of other words to capital. For example, myAge, myName, johnMarks.
- Pascal Case: In pascal case, we capitalize the first letter of every word. For example, MyAge, MyName.
- Snake Case: In snake case, we separate words by underscores (_). For example, my_age, my_name.
Note: We have learnt about primitive datatypes like int, double, float, string, char and bool etc. There are other datatypes derived datatypes like array, pointer and user defined datatypes like class, structure, enum etc which are not in scope of this chapter.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP