The Wayback Machine - https://web.archive.org/web/20240828110659/https://www.geeksforgeeks.org/cpp-variables/
Open In App

C++ Variables

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Variables in C++ is a name given to a memory location. It is the basic unit of storage in a program. 

  • The value stored in a variable can be changed during program execution.
  • A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
  • In C++, all the variables must be declared before use.

 How to Declare Variables?

A typical variable declaration is of the form: 

// Declaring a single variable
type variable_name;

// Declaring multiple variables:
type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore ‘_’ character. However, the name must not start with a number. 

Variables in C++

Initialization of a variable in C++

In the above diagram,  

datatype: Type of data that can be stored in this variable. 
variable_name: Name given to the variable. 
value: It is the initial value stored in the variable.  

Examples:  

// Declaring float variable
float simpleInterest;

// Declaring integer variable
int time, speed;

// Declaring character variable
char var;

We can also provide values while declaring the variables as given below:

int a=50,b=100;  //declaring 2 variable of integer type    
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type

Rules For Declaring Variable

  • The name of the variable contains letters, digits, and underscores.
  • The name of the variable is case sensitive (ex Arr and arr both are different variables).
  • The name of the variable does not contain any whitespace and special characters (ex #,$,%,*, etc).
  • All the variable names must begin with a letter of the alphabet or an underscore(_). 
  • We cannot used C++ keyword(ex float,double,class)as a variable name.

Valid variable names:

int x;   //can be letters 
int _yz; //can be underscores
int z40;//can be letters

Invalid variable names:

int 89; Should not be a number   
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED

Difference Between Variable Declaration and Definition

The variable declaration refers to the part where a variable is first declared or introduced before its first use. A variable definition is a part where the variable is assigned a memory location and a value. Most of the time, variable declaration and definition are done together.
See the following C++ program for better clarification: 

C++
// C++ program to show difference between
// definition and declaration of a 
// variable
#include <iostream>
using namespace std;

int main()
{
    // this is declaration of variable a
    int a;
  
    // this is initialisation of a
    a = 10;
  
    // this is definition = declaration + initialisation
    int b = 20;

    // declaration and definition
    // of variable 'a123'
    char a123 = 'a';

    // This is also both declaration and definition
    // as 'c' is allocated memory and
    // assigned some garbage value.
    float c;

    // multiple declarations and definitions
    int _c, _d45, e;

    // Let us print a variable
    cout << a123 << endl;

    return 0;
}

Output
a

Time Complexity: O(1)

Space Complexity: O(1)

Types of Variables

There are three types of variables based on the scope of variables in C++

  • Local Variables
  • Instance Variables
  • Static Variables
Types of Variables in C++

Types of Variables in C++


Let us now learn about each one of these variables in detail.  

  1. Local Variables: A variable defined within a block or method or constructor is called a local variable. 
    • These variables are created when entered into the block or the function is called and destroyed after exiting from the block or when the call returns from the function.
    • The scope of these variables exists only within the block in which the variable is declared. i.e. we can access this variable only within that block.
    • Initialization of local variables is not mandatory, but it is highly recommended to ensure they have a defined value before use.
  2. Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. 
    • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
    • Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.
    • Initialization of Instance Variable is not Mandatory.
    • Instance Variable can be accessed only by creating objects.
  3. Static Variables: Static variables are also known as Class variables. 
    • These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
    • Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
    • Static variables are created at the start of program execution and destroyed automatically when execution ends.
    • Initialization of Static Variable is not Mandatory. Its default value is 0
    • If we access the static variable like the Instance variable (through an object), the compiler will show the warning message and it won’t halt the program. The compiler will replace the object name with the class name automatically.
    • If we access the static variable without the class name, the Compiler will automatically append the class name.

Instance Variable Vs Static Variable

  • Each object will have its own copy of the instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create.
  • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all objects of a class.
  • We can access instance variables through object references and Static Variables can be accessed directly using the class name.
  • The syntax for static and instance variables:
class Example
{
static int a; // static variable
int b; // instance variable
}


Previous Article
Next Article

Similar Reads

Can Global Variables be dangerous ?
In a small code, we can track values of global variables. But if the code size grows, they make code less understandable (hence less maintainable). It becomes difficult to track which function modified the value and how. C/C++ Code // A C++ program to demonstrate that a // global variables make long code less // maintainable. int c = 1; int fun1()
2 min read
C++ 17 | New ways to Assign values to Variables
C++ 17 introduced many new ways to declare a variable. Earlier assignment and declaration was done using "=" Example: int a = 5; But now 2 more ways are introduced in C++17. They are: Constructor initialization: In this way, the value of the variable is enclosed in parentheses ( () ). In this way, value can be passed in two ways shown below. #inclu
2 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
How to return local variables from a function in C++
In C++, returning a local variable from a function may result in an error due to the deallocation of variable memory after some value is returned from the function. But there are some ways using which we can safely return the local variables or the address of local variables and manipulate the data from the caller function. In this article, we will
4 min read
Inline Variables in C++ 17
An inline variable in C++ is a variable that is declared using an inline specifier. It is an exception to one definition having multiple definitions across various translation units. Inline variables have an external linkage when not declared as static. Syntaxinline data_type variable_name = initial_value;Note: If there are multiple definitions of
3 min read
C++ Global Variables
Prerequisites: Scope of Variables, Data Types, and Functions in C++ In C++ programming languages, a variable is a name provided to memory to store different data types. Variable values can change anytime while running the program and each variable has its own scope (or region) where it is valid to access the variable using the name given to him. In
4 min read
Templates and Static variables in C++
Function templates and static variables: Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; void fu
2 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
Scope of Variables in C++
In general, the scope is defined as the extent up to which something can be worked with. In programming also the scope of a variable is defined as the extent of the program code within which the variable can be accessed or declared or worked with. There are mainly two types of variable scopes: Local VariablesGlobal Variables Now let's understand ea
5 min read
Condition Variables in C++ Multithreading
In C++, the condition variable is a synchronization primitive that is used to notify the other threads in a multithreading environment that the shared resource is free to access. It is defined as the std::condition_variable class inside the &lt;condition_variable&gt; header file. Prerequisite: C++ Multithreading, Mutex in C++. Need for Condition Va
3 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
vector erase() and clear() in C++
Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
std::sort() in C++ STL
We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access) It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The
6 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the &lt;set&gt; header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
The C++ Standard Template Library (STL)
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. Working knowledge of template classes is a prerequ
5 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :