Variables in C++

In this article, we will learn about variables in C++.

In a program, the basic unit of storage is a variable. It is a name given to a location in memory that stores some data.
While program execution, we can change the value stored in a variable.

Naming a Variable in C++

There are some rules to name a variable in C++

  • We can start a variable name with an alphabet or an underscore but not with a digit
  • Variables are case sensitive in C++
  • We must not include any special character, symbol or whitespaces in a variable name
  • Within a scope, all variables should have unique names
  • We cannot use a keyword as a variable name.

For example,

Some valid variable names are age, _city, student_name, str, etc.

Some invalid variable names are 5age, student name, student@name, string, etc.

Variable Definition and Declaration in C++

We must know that there is a difference between declaring a variable and defining it. When we declare a variable, we introduce it to the compiler before its use. Whereas, defining a variable means when memory is allocated and a value is assigned to it in the program.

Usually, both declaration and definition are done together.

Let’s declare and define a variable in C++,
Syntax:

data_type variable_name;

Here, data_type specifies the size and type of data a variable can store.

If we want multiple variables of same data type, we can define them as

data_type variable_name1, variable_name2, variable_name3;

Let’s see some examples,

int age; //a variable named age and type integer

char answer; //a variable named answer and type character

In these examples, variables age and answer are assigned some garbage value.

Variable Initialization in C++

When we assign some initial value to a variable, it is called variable initialization.

Syntax for declaring and initializing a variable in the same line:

data_type variable_name = value;

For example,

int age = 10;

We can initialize an already declared variable age as
age = 10;

Variable Scope in C++

The scope of a variable in programming is the range of visibility, out of which the variable cannot be accessed.

Variables declared inside main() in C++ cannot be accessed from outside it. A variable’s scope is confined to the curly braces that contain it; attempting to access it from outside will result in a compilation error.

Variables in C++ can be one of two types, depending on their scope:

1. Local Variables in C++

Local variables are variables that are declared within a function or code block. They can only be used by statements that are included within that function or block. They do not exist outside that function or block.

Initializing Local Variables

When we define a local variable, we need to initialize it. The system does not auto initialize it.

Example of local variables in C++

#include <iostream>
using namespace std;

void fun() {
    int total = 100;    //Local to fun()
    cout<<total;
}
int main() {
  cout<<"Total = "<<total;    
  return 0;
}

Status Compilation error
Output

In function ‘int main()’:
error: ‘total’ was not declared in this scope

Corrected Program

#include <iostream>
using namespace std;

void fun() {
    int total = 100;    //Local to fun()
    cout<<total;
}
int main() {
  cout<<"Total = ";
  fun();
  return 0;
}

Output

Total = 100

2. Global Variables in C++

Global variables are accessible from anywhere in the program. These are available until the lifetime of the program ends. These variables are normally defined at the top, outside all functions and blocks.

Initializing Global Variables

While defining a global variable if we do not assign any value to it, it is initialized by the system automatically. The values assigned are:

Data Type Initializer
int 0
char ‘\0’

Example of global variables in C++

#include <iostream>
using namespace std;

int g = 15;     //global variable

int main() {
  cout<<"Value of global variable = "<<g<<endl;
  g*=2;
  cout<<"Modified value of global variable = "<<g;
  return 0;
}

Output

Value of global variable = 15
Modified value of global variable = 30

When a Local and a Global variable have same name

Example to illustrate when a local and a global variable have same name

#include <iostream>
using namespace std;

int var = 15;     //global variable

int main() {
  int var = 2;        //local variable
  cout<<var;
  return 0;
}

Output

2

When a local and a global variable have the same name, we can access the global variable using scope resolution operator (::).

Example to show how to access a global variable when its name is same as that of a local variable

#include <iostream>
using namespace std;

int var = 15;     //global variable

int main() {
  int var = 2;        //local variable
  cout<<"Global variable = "<<::var<<endl;
  cout<<"Local variable = "<<var;
  return 0;
}

Output

Global variable = 15
Local variable = 2

Some other types of variables in C++

1. Static Variables in C++

Static variables are defined using the static keyword. These retain their value even when they are no longer in use. They are only initialized once and exist till the program is terminated. They are local to the function in which they are defined.

Default initial value of a static variable is 0.

Example of static variables in C++

#include <iostream>
using namespace std;

void sfun() {
    int a = 10;
    static int b = 10;
    cout<<"a = "<<a++<<"    ";
    cout<<"b = "<<b++<<endl;
}

int main() {
  for(int i=0; i<3; i++) {
      sfun();
  }
  return 0;
}

Output

a = 10 b = 10
a = 10 b = 11
a = 10 b = 12

Observe that unlike the variable a, static variable b does not reinitialize. It retains its value.

2. Automatic Variables in C++

Using the auto keyword, the data type of a variable is automatically deducted by the compiler from the value assigned to it.

Scope of auto variables is local to the function in which they are defined. Their default initial value is garbage value.

For example:

auto n = 10;
auto word = “TechVidvan”;

3. External Variables in C++

The extern keyword simply indicates that the variable is defined outside of the block in which it is being used. It is a global variable that is declared and initialized to be used somewhere else. The key purpose of extern variables is that they can be accessible from two separate files inside a larger program.

Their default initial value is 0.

Example of extern variable in C++

#include <iostream>
using namespace std;

int x;

void efun() {
    extern int x;       //Indicating that x is defined elsewhere
    x = 2;              //Modifying the value of x
    cout<<"Modified value of extern variable x = "<<x;
}

int main() {
    cout<<"x = "<<x<<endl;
  efun();
  return 0;
}

Output

x = 0
Modified value of extern variable x = 2

Summary

This article covers all about variables in C++.

We learnt the rules to name a variable, how to define and initialize it. Then, we learnt about the scope of variables in C++. On the basis of scope, variables are of two types namely, local variables and global variables. We understood how to handle local and global variables with examples.

We also discussed the situation when a local variable and a global variable have the same name. Lastly, we learnt about static, automatic and external variables.