1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
3

C++ Variable: A Guide

Updated on 18/09/2024415 Views

A variable is a fundamental building block in programming. We can think of it as a named container that resides in our computer's memory. This container can hold different types of data, just like a box can hold various items.

For example, let us assume that we have a set of labeled boxes. One might be labeled "Age," another "Name," and yet another "Favorite Color". Each box can store a specific type of information. A variable is similar, it has a name (like the box label) and holds a value of a specific type (like the contents of the box).

Let us learn more about the different types of variables in C++ and how we can use them effectively in C++ programming.

C++ Variable Key Points

Here are some key points associated with using a C++ variable:

  • Named Container: Every variable has a unique name you choose to identify it.
  • Memory Location: The variable's name represents a specific spot in memory where the value is stored.
  • Data Types: Variables can hold different types of data, such as numbers (integers, decimals), characters, or true/false values.
  • Changeable: The value stored in a variable can be modified throughout our program's execution.

What is Variable in C++ with Example

A C++ variable serves the same purpose in the world of C++ programming as variables in other scripting/programming languages. We use various different variables to store all kinds of information to be used in C++ programs. 

Example:

int age = 25;     // Variable to store a person's age

std::string name = "Alice"; // Variable to store a person's name

// Using the variables

std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl; 

In this C++ string variable example, age and name are variables. The program can then use these variables to display a personalized greeting.

C++ Variable Types

C++ offers a wide range of variable types to store different kinds of data. Understanding these types is crucial for writing efficient and correct code. Let us look at the are the common C++ variable types.

Built-in Data Types

These are fundamental data types provided by C++ to represent common forms of information:

  • Integers (int): Integers store whole numbers without decimal points. They can be positive, negative, or zero. Examples: 5, -12, 0.
  • Variations: C++ provides variations of int with different storage sizes (and therefore ranges): short int, long int, long long int.
  • Floating-Point (float, double): Floating-point numbers represent values with decimal points. They are essential for scientific calculations and any situation where fractions or precise measurements are needed. Examples: 3.14, -0.25, 2.9979e8 (scientific notation). double typically offers higher precision than float.
  • char: The char type stores single characters enclosed in single quotation marks. Examples: 'A', '!', '$'. Each character is internally represented by a numeric code (ASCII or Unicode).
  • bool: Boolean variables represent logical values: true or false. They are fundamental for decision-making and control flow in our programs.

Custom Data Types

C++ lets us create our own data types tailored to our specific needs:

  • Structures (struct): Structures group related variables of different data types together. For example, a struct named Person might contain variables for name (string), age (integer), and height (float).
  • Classes: Classes are similar to structures but also include functions (methods) that operate on the data. They are the foundation of object-oriented programming in C++.
  • Enumerations (enum): Enumerations define a set of named integer constants. They are useful for representing a fixed set of options or states. For example, an enum named Day might have values like Monday, Tuesday, etc.

Declaring and Initializing a C++ Variable

Before we can use a C++ variable in our program, we need to introduce it to the compiler. This involves two steps:

  • C++ Declare Variable: This tells the compiler the variable's name and its data type.
  • C++ Initialize Variable (Optional): This assigns an initial value to the variable. While not always mandatory, it's highly recommended for better code reliability.

Syntax:

dataType variableName = initialValue;

In the above C++ variable syntax:

  • dataType: Specifies the type of data the variable will hold (e.g., int, double, char, bool).
  • variableName: The unique identifier we choose for our variable.
  • initialValue: The starting value we want to store in the variable.

Example:

int age = 25;        // Declares an integer variable named 'age' and initializes it with the value 25.

double price = 9.99; // Declares a double variable named 'price' and initializes it with the value 9.99.

char grade;          // Declares a character variable named 'grade' (not initialized).

Example in a program structure:

#include <iostream>

#include <string>

int main() {

    int age = 30;             // Integer

    double weight = 75.5;     // Floating-point

    char grade = 'A';         // Character

    bool isStudent = true;    // Boolean

    std::string name = "Alice"; // Custom type: String

    // ... your code here ...

    return 0;

}

Importance of Data Type in C++ Variable

The data type we choose for a variable is crucial:

  • Memory Allocation: It determines the amount of memory reserved for the variable. For instance, an int typically uses 4 bytes of memory, while a double might use 8 bytes.
  • Value Restrictions: The data type defines the kind of values the variable can hold. An int can only store integers, while a char can only store a single character. Trying to assign an incompatible value can lead to errors.

Naming Conventions for Using a C++ Variable

Choosing appropriate names for our variables is essential for code readability and maintainability. Here are some best practices:

  • Be Descriptive: Use names that reflect the purpose of the variable (e.g., numberOfStudents, totalPrice, isValid).
  • Use Camel Case: Start with a lowercase letter and capitalize the first letter of each subsequent word (e.g., firstName, studentAge, isGameOver).
  • Avoid Reserved Words: Don't use keywords that have special meaning in C++ (e.g., int, double, if, else).
  • Be Consistent: Follow a consistent naming style throughout our codebase.

In C++, we can declare a variable without initializing it. However, this can lead to undefined behavior because the variable might contain a garbage value from memory. It's generally good practice to initialize variables with a default value when we declare them.

Example of C++ Variable in a Program

Now that you are aware of how many types of variables in C++ exist, let us look at a C++ variable example program that you can run and try out yourself:

C++ variable example

Code:

#include <iostream>

int main() {

    // Variable Declaration and Initialization

    double celsius = 25.0;      // Temperature in Celsius

    double fahrenheit;          // Variable to store the converted temperature

    const double CONVERSION_FACTOR = 9.0 / 5.0; // Constant for conversion formula

    // Calculation

    fahrenheit = (celsius * CONVERSION_FACTOR) + 32.0;

    // Output

    std::cout << "Temperature in Celsius: " << celsius << "°C" << std::endl;

    std::cout << "Temperature in Fahrenheit: " << fahrenheit << "°F" << std::endl;

    return 0;

}

In the above C++ variable example, we use double celsius = 25.0; to declare a variable named celsius of the double data type (floating-point number). We assign the initial value 25.0 to the celsius variable. Similarly, we use double fahrenheit; to declare another variable named fahrenheit of the double data type. We declare the variable but do not assign an initial value to it as it will be assigned later after the conversion.

If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.

Advanced C++ Variable Concepts

While the basics of variables are essential, C++ offers some advanced features that give you more control over their behavior and usage. Let us explore some advanced C++ variable concepts.

Modifiers

Modifiers are keywords that we can apply to variable declarations to change their properties:

  • const (Constant): When we declare a variable as const, we are creating a constant variable. This means its value cannot be changed after it's initialized. Constants are useful for storing values that shouldn't be modified during program execution, like mathematical constants (e.g., PI) or configuration settings.

Example:

const double PI = 3.14159;

PI = 3.0;  // Error! You can't change the value of a const variable.

  • static (Static): The static modifier is primarily used with local variables declared inside functions. By default, local variables are created and destroyed each time a function is called. However, a local C++ static variable retains its value between function calls. It acts like a C++ global variable within the scope of that function. We can combine a C++ class variable with the static modifier to work on a class. This creates a C++ static variable in class.

Example:

void myFunction() {

    static int counter = 0; 

    counter++;  // This value persists between function calls

    std::cout << "Function called " << counter << " times." << std::endl;

}

References

A reference is an alias (another name) for an existing variable. It's like a nickname for the C++ variable, and any changes made through the reference directly affect the original variable.

Example:

int originalValue = 10;

int& refValue = originalValue;  // Declare a reference to originalValue

refValue = 20;  // Modifies originalValue through the reference

std::cout << originalValue;  // Output: 20

Pointers

A pointer is a variable that stores the memory address of another variable. It is like having a signpost that points to the location where the data is stored.

Example:

int num = 5;

int* ptr = &num; // Declare a pointer named 'ptr' and assign it the address of 'num'

std::cout << *ptr;  // Output: 5 (dereferencing the pointer to get the value)

Why Use Variables?

Different C++ variable types are indispensable in programming for several reasons:

  • Storing User Input: When our program interacts with a user, we use variables to capture and store the information they provide (e.g., their name, age, or preferences).
  • Tracking Program State: Variables are used to keep track of the current state of our program. For instance, a variable might indicate whether a user is logged in, the current score in a game, or the progress of a download.
  • Performing Calculations: Variables hold the values we use in mathematical operations. We can add, subtract, multiply, and divide the values stored in variables.
  • Making Code Reusable: By using variables, we can write code that works with different values each time it runs. For example, a function that calculates the area of a rectangle can be reused with different width and height values by using variables.

Final Tips

Fundamentally, variables are named containers in memory that store data of different types, enabling programs to manipulate and track information throughout their execution. They are fundamental for capturing user input, performing calculations, and making code adaptable to various scenarios.

Finally, according to me, choosing appropriate data types and meaningful names is absolutely crucial for writing clear and efficient code. If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.

Frequently Asked Questions

  1. What is a variable in C++?

If we had to define variable in C++, we could define it as a named memory location that stores a value of a specific data type. It acts as a container to hold and manipulate data during the execution of a program. 

  1. How do you declare a variable in C++?

You declare a variable in C++ by specifying its data type followed by the variable name, optionally followed by an initial value (e.g., int age = 25;).

  1. What are the different types of variables in C++?

C++ has built-in data types like int, double, char, and bool, as well as custom data types like struct, class, and enum.

  1. Can a variable's value be changed in C++?

Yes, you can change the value of a variable in C++ unless it's declared as const.

  1. What are the rules for naming variables in C++?

Variable names in C++ must start with a letter or underscore, can include letters, numbers, and underscores, and should not be reserved keywords.

  1. Do variables in C++ have to be initialized when declared?

While it's not strictly required to initialize variables when declared, it's good practice to do so to prevent undefined behavior.

  1. What is the scope of a variable in C++?

The scope of a variable in C++ can be local (limited to a block of code) or global (accessible throughout the program).

  1. Can variables in C++ have different data types?

Yes, variables in C++ can have different data types depending on the kind of information they need to store.

Rohan Vats

Rohan Vats

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming eng…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...