×

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

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 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.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.