×

C++ Variable

In this article, we will discuss variables in C++ with their types and examples.

What are Variables?

Variables are specific memory storage spaces that hold a value. During the execution of a program, variables might have their values altered. Programming requires variables because they enable the storage, retrieval, and modification of data.

A C++ variable is a specific memory area that contains data that can be altered while the program is active. Variables act as containers for a wide range of values in computations and logic operations.

C++ variables are used to store data in a memory location. The value stored in the variable may be changed depending on program execution. Each variable in a programming language has its own specific types. These specific data types determine the size and layout of the variable's memory.

In C++, variable definition tells the compiler:

  • How much memory should be set up for the variable?
  • Where in the RAM should the variable be created and stored?
  • The type of values that a variable can store depends on its data type.

A variable definition consists of:

  • A data type (char, float, int, etc.).
  • A name for a variable (identifier).
  • A starting value is optional.

Characteristics of Variables in C++:

Several characteristics of Variables in C++ are as follows:

1. Memory allocation:

  • When a variable is declared, the compiler uses its data type to calculate how much memory it will require.
  • Each variable has a unique address in memory.

2. Modification of Value:

  • While a program is executing, variables might have their values altered.

3. Data types association:

  • The data type that each variable is assigned to determines the kind of data that it can store.
  • The kind of data that can be stored by a variable is determined by its data type (text, numbers, etc.).

4. Uniquely Identified:

  • Variables are referred to in a program by their names or identifiers.

Declaration of variables in C++:

data_type variable_name = value;

Types of variables in C++:

Several types of variables in C++ are as follows:

  • Local variables: These variables will be in the scope of the block or function where they are defined.
  • Global variables: These are declared outside all functions. These variables will be accessible from any place in the program.  
  • Static variables: It maintain their value in between calls to functions.
  • Constant variables (const): Once initialized, their values cannot be altered.

Rules of C++ Variable declaration:

1. C++ variable name can be declared with small letters a-z, capital letters A-Z, digits 0-9, and underscore character.

In a C++ Variable name consists of:

  • Lower-case letters: a-z
  • Upper-case letters:A-Z
  • Digits:0-9     
  • Underscore:_

Valid Example Syntax:

int value;          // Uses lowercase letters

float Pi_Value;   // Uses uppercase and underscore

double distance_2030; // Contains digits and an underscore

Invalid Example Syntax:

int @value;      // Invalid: Contains special character '@'

float amount#;    // Invalid: Contains '#'

double 2distance;   // Invalid: Starts with a digit

2. First letter of variable must be underscore or letter.

  • A variable name must start with an underscore (_) or a letter (a-z or A-Z).
  • It cannot be started with any of the numbers 0–9.

Valid Example Declaration:

int number;        // Starts with a letter

float _Weight;  // Starts with an underscore

Invalid Declaration:

int 9number;   //  Invalid: Cannot start with a digit

double *price;  // Invalid: '*' is not allowed

3. C++ is a case-sensitive. Capital and small letters are treated differently.

C++ takes uppercase and lowercase letters as different:

Example:

int score = 35;

int Score = 40;

int SCORE = 45;

cout << score << endl;  // Outputs 35

cout << Score << endl;  // Outputs 40

cout << SCORE << endl;  // Outputs 45

What to avoid while declaration of a variable:

  • Variable declaration cannot be started with digits 0-9.
  • Special characters such as $, # are not allowed.
  • C++ keywords cannot be used as variables.
  • Blank space cannot be used as variables.

Some of the invalid syntaxes should be followed while declaration of a variable:

int 1number;  // Error: Cannot start with a digit

float total#;  // Error: '#' is not allowed in variable names

double @price; // Error: '@' is not allowed

char first-name; // Error: '-' is not allowed (interpreted as subtraction)

Example Code:

Let us take an example to illustrate the variables in C++.

#include <iostream>

using namespace std;

int main() {

    // Defining different types of variables

    int age = 25;           // Integer variable

    float pi = 3.14;        // Floating-point variable

    double price = 99.99;   // Double precision floating-point variable

    char grade = 'A';       // Character variable

    bool isPassed = true;   // Boolean variable (true/false)

    // Displaying variable values

    cout << "Age: " << age << endl;

    cout << "Pi Value: " << pi << endl;

    cout << "Price: " << price << endl;

    cout << "Grade: " << grade << endl;

    cout << "Passed: " << isPassed << endl;

    return 0;

}

Output:

Age: 25

Pi Value: 3.14

Price: 99.99

Grade: A

Passed: 1

Conclusion:

In C++, variables are very important in controlling data and storage at different stages of the program in C++. When a variable is defined, it will inform the compiler where the variable will be stored and how much memory it will allocate up to the data type of the variable. The data type restricts the size and type of values that can be assigned to a variable. These include character values char, boolean values bool, floating-point values float, and double and integer values int. A variable can be declared and defined and introduced to another point in time. A good understanding of variable declaration, initialization, and memory allocation leads to programming efficiently and without mistakes. Following naming conventions and best practices enable developers to create C++ code that is understandable, readable, and maintainable.


Related Topics

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

How to Reverse a String in C++ using While Loop

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer...

6 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.