Variables in C++

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

Variables are the most essential part of any programming language. Variables are simply the name given to memory locations that are used to store values in a computer program. Variables are declared based on some rules which we will be discussing in this article as well as how the compiler interprets a variable and we will also learn about the basic types of variables as well as variable scope.

Scope

In this article, we will understand variables in depth i.e.

  1. We will answer questions like how variables are declared and initialized, what happens internally in the computer system when we define variables.
  2. We will also learn about the rules for defining variables.
  3. We will also cover concepts like L values and R values as well as the scope of variables.
  4. At last, we will understand types of variables based on their accessibility.

What are Variables in C++?

Variables are the most important part of any programming language. Any programming language is incomplete without variables.

With variables, it is easy to remember the values. Let's say we need to remember values like 4 and 5 and later in the program we need to perform arithmetic operations on 4 and 5 like add 2 to 4 and subtract 1 from 5, as we can see this task is hectic but with the help of variables, we can store these values and easily perform arithmetic operations.

Variable is basically the name of the memory location that stores data. Every variable has a data type and a value associated with it which we could change any number of times during program execution and a variable can be reused many times in a program.

Variable represents memory location through a symbol which helps us to identify the memory location easily. Variables can be of any data type. We could also change the value of the variable as many times as we want.

Basic types of Variables in C++

S.NoTypeDescriptionMemory(in bytes)Range
1.boolstores either true(1) or false(0)10 or 1
2.charstores a single character such as 'a' or 'A' surrounded by single quotes.10 to 255
3.wchar_tstands for wide character. Stores a single character which takes more space than normal characters. Char is of 1 byte but wchar_t is of 2-4 bytes depending on compiler20 to 65,535
4.intstores integers such as 45 or -344-2,147,483,648 to 2,147,483,647
5.floatstores floating-point values.41.2E-38 to 3.4E+38
6.doublestores floating-point values with more precision than float.82.3E-308 to 1.7E+308
7.stringstores text such as "Hello World" surrounded by double quotes.depends on size of string

Note: Apart from above predefined data types, there are user defined variables also defined using struct and class.

Declaring Variables in C++

General syntax :

datatype var = val;

Here, datatype specifies the type of the variable like int, float, etc.
var is the variable name.
val is the value which the variable var of type datatype holds.

Example:

int val = 5;

This is the integer variable with the name val and holds value 5.

We can declare single or multiple variables.

  • Single variable

Syntax:

datatype var;

Example:

  int age;
  bool isValid;
  double pecentage;
  int arr[5]; (integer array variable)
  • Multiple variables in a single line

Syntax:

datatype var1, var2, ... varn;

Example:

int length, breadth, height;

Initializing Variables in C++

We can initialize a value to a variable at the time of declaration and later also.

  • Initializing at the time of declaration

    In this method, we simply assign value to the variable at the time of declaration.
int age = 24;
float percentage = 85.4;
bool isValid = true;
  • Initializing after declaration

    In this method, we do not assign value to the variable at the time of declaration, we assign it later in the program.
 int a, b, c;
 a = 5;  
 b = 10;
 c = a + b;

The only difference between the above two methods is that when we do not assign any value at the time of declaration then a garbage value is assigned to the variable by the compiler.

How do Variables Work in C++ ?

  1. Declaration of variables tells the compiler about the data type and after knowing the data type compiler will reserve a memory space required by the type.
  2. Declaration of variables also tells the compiler about the name of the variables that will be used in our program.
  3. After the reservation the compiler gives the address of that location to that variable.

Example:

int age = 24;

After knowing data type int, the compiler will reserve 4 bytes(depends on the compiler) of space in the memory. Then, the compiler stores the address of that location in variable age. After reading value 24, the compiler will assign value 24 to the variable age.

Rules for defining Variables in C++

  1. Variable name should contain only letters, digits, or underscore(_).
  2. Variable name should start with a letter or underscore only. It cannot start with a digit.
  3. Variable name should not contain any white spaces or characters like !, #, %, etc.
  4. Variable names are case sensitive i.e age and Age are two different variables.
  5. Keywords or Reserved words cannot be variable names.

Some valid variable names:

age, length, car_color, isValid.

Some invalid variable names:

  1. 1var(starts with a digit)
  2. mother age (contains white space)
  3. int (keyword)

Difference between variable declaration and definition

DeclarationDefinition
1. Tells the compiler about the name and data type of the variable only.1. Tells the compiler about the name and data type of the variable as well as the memory location of the variable.
2. We can declare a variable multiple times.2. We can define a variable only once.
3. Example:
extern int age; 
This declaration tells the compiler that the variable age is declared but the memory for variable age will be defined later in the same file or in a different file.
3. Example:
 int age = 24;  
This variable definition tells the compiler that the variable age is declared and it is used for allocating memory for the variable.

Example:

int age = 24;

The above is a variable declaration as well as a definition.

int height; 

The above is also variable declaration as well as definition, some garbage value is assigned to it.

In C++, the declaration and definition are always done together because when we declare a variable without initializing it then a garbage value is assigned to it.

With the extern keyword, a variable is only declared but the memory is not allocated to the variable.

For Example,

extern int age;

This is variable declaration only.

LValues and RValues

Every Expression in C++ is either Lvalue or Rvalue expression.

Lvalue: If you can take the address of expression then it is Lvalue, and they last until their scope. Lvalues represent the objects that occupy space and have some memory location/address associated with them.

Rvalue: If you can't take the address of expression then it is Rvalue. They don't exist after one line or expression and also do not refer to a memory location.

Note: The lvalue can come either on the right-hand side or left-hand side of an assignment statement but the Rvalue can only come on the right-hand side.

Example:

1. int x = 10;  //x is Lvalue and 10 is Rvalue.
   int* ptr = &x; //we can take address of x in ptr because x is Lvalue.
2. int a = 5, b = 15;
   int y = a + b; 
   // y is Lvalue and (a + b) is Rvalue.
   int* ptr = &(a+b); //error because (a+b) is Rvalue.

Scope of Variable

The scope is simply a block or region where a variable is defined and can be used, and when the block or region ends, the variable is destroyed i.e the memory assigned to that variable in the system is released.

There are two types of variable scopes :

1. Local variables

Any variable define inside { } (region or block) is a local variable for that region and they cannot be accessed outside this region.

2. Global variables

Any variable defined outside all the functions or blocks is a global variable, and it can be accessed by any of the functions. They are self initialized, i.e if a global variable is of int data type, then it is initialized with 0.

Example :

#include<bits/stdc++.h>
using namespace std;

// this is a global variable
int var = 20;

int main() {
  // this is a local varible
  // its scope is within main function only
  int x = 10;

  if (x <= 10) {
    // here y is a local variable 
    // whose scope exists within this if block
    int y = 2;

    cout << x * y;
  }

  return 0;
}

In the above code, there are two types of variable scope i.e global variable var whose scope exists until the program terminates, and local variable x whose scope exists until the main function ends.

Types of Variables in C++

  • Local variable

    1. These are the variables defined within a block, function, or method.
    2. They are accessible within that block and get destroyed when the block ends i.e memory assigned to the variable is released.
    3. Initialization of this type of variable is mandatory, if we don't do it, the compiler does it itself and gives it a garbage value.
    Example:
#include<bits/stdc++.h>
using namespace std;

int main() {
  // local variable whose scope 
  // exist inside main function only
  int a = 10;

  return 0;
}
  • Instance variable

    1. These are non-static variables declared in a class outside constructors, methods, and other blocks.
    2. They get memory when the object of that class in which they are declared is created and destroyed when the object is destroyed.
    3. Their initialization is not compulsory while declaring, by default they will have garbage values.
    4. Every object of the class gets a separate copy of their instance variables.
    5. The scope of the instance variable is controlled by the access specifier which is the inbuilt functionality of the class.
    Example:
#include<bits/stdc++.h>
using namespace std;

class student {
  public:
    // instance variables
    int roll_no;
    string name;
    int marks;
};

int main() {
  // defining object of the
  // class student
  student s;

  return 0;
}
  • Static variable

    1. These are similar to instance variables but common to every object of the class, in other words, there is only a single copy of static variable per class and static variables are declared with a static keyword.
    2. They get memory at the start of the program and get destroyed when the program ends.
    3. The static variables are stored in the data segment of the memory.
    4. Their initialization is compulsory and it is done outside the class, by default int variable will have 0 value, boolean will have false.

    Example:

#include<bits/stdc++.h>
using namespace std;

class student {
  public:
    // static variable 
    static int passing_marks;
};

int student::passing_marks = 33;

int main() {
  // definining object of the
  // class student
  student s;

  return 0;
}
  • Automatic variables

    1. Variables declared with auto keyword are automatic variables.
    2. Auto keyword specifies that the type of the variable that is being declared will automatically be deduced from its initializer.
    3. The difference between normal and auto variable is that for the normal variable, the user has to specify datatype and with auto keyword, the datatype is automatically deduced by the compiler.
    Example:
#include<bits/stdc++.h>
using namespace std;

int main()
{
   // automatic variable
   auto b = 10;
   
   return 0;
}
  • External variable

    1. Variables declared with extern keyword are external variables.
    2. It is used when a particular file needs to access a variable from another file i.e. if there is a variable defined in another file let's say file_1 and we are writing a program in another file i.e. file_2, then we can use the variable defined in file_1 in our file_2 by using extern keyword and including header file of file_1 in file_2.
    3. It is used for variable definition only i.e. variable declared with extern keyword does not get any memory.

    Example:

int main()
{
   // this variable is defined in another
   // file but in this file it is only declared 
   extern int age;
   return 0;
}

Difference between Instance and Static Variable

Instance variableStatic variable
1. Declared in a class outside constructors, methods, and other blocks.1. Similar to instance variables but common to every object of the class and are declared with a static keyword.
2. They get memory when the object of that class in which they are declared is created and destroyed when the object is destroyed.2. They get memory at the start of the program and get destroyed when the program ends.
3. Every object of the class gets a separate copy of their instance variables3. There is only a single copy of static variable per class i.e static variables get memory only once and not again and again when different objects of a class are created.
4. Their initialization is not compulsory.4. Their initialization is compulsory and it is done outside the class.
5. To access the instance variable we require an object reference of that class.5. A static variable could be accessed using the class name.

Conclusion

In this article we learned about:

  1. Variables store data and can be of many types like int, float, etc and user-defined variables are also present.
  2. Value can be assigned to a variable at the time of variable definition otherwise garbage value is assigned if we do not assign value.
  3. Difference between variable declaration and definition. Declaration specifies variable's data type and names whereas definition allocates memory too.
  4. Working of variables in C++ where the type of variable specifies memory space needed by the variable.
  5. Rules for defining variables that specify what variable names are allowed by the compiler.
  6. RValue does not refer to a memory location and LValue refers to a memory location.
  7. Scope of variable is of two types, namely, global and local.
  8. Types of variables are namely, instance, static, automatic, and external.
Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
Free Courses by top Scaler instructors
rcbGet a Free personalized Career Roadmap from