DEV Community

Tpoint Tech
Tpoint Tech

Posted on

Understanding Variables and Data Types in C++

Introduction:

Variables and data types in C++ are the basic building blocks of any program. They are essential for storing, manipulating, and working with data.
In any programming language, variables are containers for storing the data values, and it is the name of the memory location. These variables are used to reserve the memory location that holds the value. If the variable is created, memory space is allocated for it.
C++ is a statically typed and compiled language. However, during program execution, the identifiers of the variable’s names are lost. When a variable is defined in C++, data types define the type of data that a variable stores.

Image description

Variable in C++

A variable is a named storage location in memory that holds a value which can be changed during program execution. Variables store the data type, such as characters, floating numbers, integers, or more complex data types.
Syntax: The general syntax of the variable declaration is as follows:

data_type variable_name;
Enter fullscreen mode Exit fullscreen mode

Example (Declaration and Initialization)
Code:

int num;
int num = 50;

#include <iostream>
using namespace std;
int main () {
    int age = 13;
    cout << age << endl;
    age = 17;
    cout << age;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

13
17
Enter fullscreen mode Exit fullscreen mode

Naming Variable Rules

The given name of the variables is called identifiers. Some rules can be defined as follows:
• Variable is a case sensitive (e.g name and Name both are different)
• The Variable should start with an underscore or a letter only.
• This cannot be used C++ keyword such as double, float and class as a variable name.
• The variable name can only store letters as that (A-Z or a-z), digits (0-9) and underscores (_).

Scope of Variables in C++

In C++, a variable refers to the area of code where a variable is accessible. It determines the scope of the variable where the program can be accessed.

The scope of a variable can be defined below:

1) Local Scope: The local scope variable is used within the curly braces and is called the block scope variable. This can be accessed only within the block, not access anywhere in the program.

Syntax:

void function () {
    Type variable_Name = value; // Local variable
    // variable Name is accessible only inside this block
}
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;

void local() {
    int x = 42;  // Local variable
    cout << "Block type of function: local Variable = " << x << endl;
}

int main() {
    local();
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Block type of function: local Variable = 42
Enter fullscreen mode Exit fullscreen mode

2) Global Scope: Global Scope can be accessed outside any function or a block. If you are declared the variable at one time, you can access the variable in the entire program.

Syntax:

Type variableName = value; // Global variable

void function () {
    // variableName is accessible anywhere in the 
}
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;

// Global variable
int num = 100;

void show() {
    cout << "Inside show(): global Variable = " << num << endl;
}

int main() {
    cout << "Inside main(): global Variable = " << num << endl;

    num = 200;

    show();

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Inside main (): global Variable = 100
Inside show (): global Variable = 200
Enter fullscreen mode Exit fullscreen mode

3) Function Scope: In C++, function scope can be referred to as the visibility and accessibility of the program.
Syntax:

Return_Type function (parameter1, parameter2……...parameter n) {
    // Function body
}
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;

void greeting() {
    cout << "Hello from greet() function is called!" << endl;
}

int main() {
    greeting();  
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello from greet() function is called!
Enter fullscreen mode Exit fullscreen mode

Data type in C++

In C++, data types occupy the nature of data a variable can hold and how much memory it stores. This supports a wide range and variety of data types.

Types of data types in C++ are as follows:

1) Primitive data types: Primitive data types are called the in-built data types or pre-defined data types that are used to store the simple values. These data types are faster compared to the other data types. There are many kinds of primitive data types, such are as follows:

Integer Data type (int): This data type is stored the integer values. It has a range of -2,147,483,648 to 2,147,483,647 and is 4 bytes (64 bits) in size. The integer data type is defined by the keyword int.

Example:

#include <iostream>
using namespace std;

int main() {
    int x = 250;
    cout << The Integer value is :" << x <<endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

The Integer value is :250
Enter fullscreen mode Exit fullscreen mode

Character Data type (char): This data type used to define a character is char. A single character is stored here. It has a range of 0 to 255 and is 1 byte (8 bits) in size.

Example:

#include <iostream>
using namespace std;

int main() {
    char c = 'Z';  
    cout << Character is :" << c <<endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Character is :Z
Enter fullscreen mode Exit fullscreen mode

Floating Data type (float): This data type is stored the decimal values. It has a range from 1.2E-38 to 3.4e+38, and size is 4 bytes (64 bits). Using the float keyword is used to declare the floating data types.

Example:

#include <iostream>
using namespace std;

int main() {        
    float f = 15.3;
    cout << Floating value is :" << f <<endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Floating value is :15.3
Enter fullscreen mode Exit fullscreen mode

Double Data type: This data type is stored the long decimal values. Its size is 8 bytes (64 bits), and it has a range 1.7e-308 to 1.7e+308. Double is the keyword that defines the double data type.

Example:

#include <iostream>
using namespace std;

int main() {
    double pi = 5.147851322;
    cout << Double value is :" << pi <<endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Double value is :5.147851322
Enter fullscreen mode Exit fullscreen mode

Boolean Data type (Bool): This data type is used to store true or false values. A true value indicates a value (1), but a false indicates for value (0). The size of the Boolean data type is 1 byte. Bool is the keyword used to define the Boolean data type. By default, the value of this data type is a false (0) value.

Example:

#include <iostream>
using namespace std;

int main() {
    int x = 5;
    int y = 10;


    bool res1 = x < y;
    bool res2 = x == y;
    bool res3 = x > y;

    cout << "x = " << x << ", y = " << y << endl;
    cout << "Is x less than y? " << res1 << endl;
    cout << "Is x equal to y? " << res2 << endl;
    cout << "Is x greater than y? " << res3 << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

x = 5, y = 10
Is x less than y? 1
Is x equal to y? 0
Is x greater than y? 0
Enter fullscreen mode Exit fullscreen mode

2) Derived Data type

These data types are created from the primitive data types and provide some additional features. The derived data type is based on the fundamental or in-built data type.

In C++, there are different types of derived data types defined below:

Functions: The function is a block of code to perform a particular task. This can be manage to organize code, improve code readability, and reduce repetition. It runs only when it is called.

Syntax:

return function (param1, param2……., param n) {
    // body of the function
    return value;
}
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

int main() {
    int x = 15, y = 20;

    int sum = add(x, y);

    cout << " The addition of two numbers is : " << sum << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

The addition of two numbers is : 35
Enter fullscreen mode Exit fullscreen mode

Arrays: An array is to store the same data type and a collection of multiple values. In array data is stored in a contiguous memory location. The index of the array starts from zero (0) to last element of the array.

Syntax:

data_type array_name[array_size];
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;

int main() {
    int n = 5;
    int arr[n] = {1,2,6,5,7};  

    int sum = 0;
    int max = arr[0];


    cout << "Array elements: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    for (int i = 0; i < n; i++) {
        sum += arr[i];

        if (arr[i] > max) {
            max = arr[i];
        }
    }

    double avg = (double)sum / n;


    cout << "\nThe sum of all the elements = " << sum << endl;
    cout << "\nAverage of all the elements = " << avg << endl;
    cout << "\nThe maximum element of the array is = " << max << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Array elements: 1 2 6 5 7 
The sum of all the elements = 21

Average of all the elements = 4.2

The maximum element of the array is = 7
Enter fullscreen mode Exit fullscreen mode

Pointers: In C++, Pointers are declared using the asterisk symbol (*). The address of the pointer (&) is used to store the memory address variable. It's a symbolic representation of the address. It can be used in any data type, such as int, char, etc.

Syntax:

data_type* name;
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;
int main() {
    int arr[5] = {1,2,3,4,5};
    int* p = arr;  

    cout << "Accessing array using pointer:\n";
    for (int i = 0; i < 5; i++) {
        cout << "element " << i << ": " << *(p + i) << endl;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Accessing array using pointer:
element 0: 1
element 1: 2
element 2: 3
element 3: 4
element 4: 5
Enter fullscreen mode Exit fullscreen mode

References: In C++, reference is used to provide an alternative name for the existing variable. It allows the users to refer to the same memory location using a different name. Also, it does not occupy new memory as it performs the direct operation of the variable.

Syntax:

data_type &reference_name = original_variable;
Enter fullscreen mode Exit fullscreen mode

Example:

#include <iostream>
using namespace std;
void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int m = 15;
    int n = 20;

    cout << "Before swap of variable :" << endl;
    cout << "m = " << m<< ", n = " << n << endl;

    swap(x, y);

    cout << "\nAfter swap of variable:" << endl;
    cout << "m = " << m << ", n = " << n << endl;

    return 0;
}
Output:
Before swap of variable :
x = 15, y = 20

After swap of variable:
x = 20, y = 15
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Understanding variables and data types is essential for every C++ programmer, as they form the foundation of all programming logic. Variables allow you to store and manipulate data, while data types ensure that the data is used correctly and efficiently.

I suggest you learn the C++ Programming from the Tpoint Tech website as this website provides C++ tutorials, interview questions, and an Online Compiler as well, which can help you to learn variable and data types in C++ in an easier way.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.