Paramclasses Academy - Blog

Tutorials Details

What is Variables, Data Types and Constants in C++

What is Variables, Data Types and Constants in C++

October 15, 2026

This module explains how C++ stores information, identifies different kinds of values, declares variables, defines constants, and accepts input from users. These concepts form the foundation for calculations, decision-making, loops and larger programs.

2.1 Learning objectives

By the end of this module, students will be able to:

  • Define variables and constants in C++.

  • Identify fundamental data types and their uses.

  • Declare, initialize and update variables.

  • Understand identifiers, keywords and naming rules.

  • Accept user input using std::cin.

  • Display results using std::cout.

  • Perform type conversion and type casting.

  • Write simple programs using variables and data types.

Prerequisites: Module 1 — Introduction to C++, including the structure of a basic C++ program.

Estimated learning time: 3–4 hours, including coding exercises.

2.2 What is a variable?

A variable is a named object that stores a value that a program can access and, when permitted, modify.

For example, a student marks program may need to store marks, a student's age and an average score. Variables let us represent these values using meaningful names.

Syntax

data_type variable_name = value;

Example:

int age = 20;
double salary = 25000.50;
char grade = 'A';

Here:

  • int specifies an integer type.

  • age is the variable name.

  • 20 is the initial value.

  • double is used for floating-point values with greater precision than float in typical implementations.

  • char represents a character value.

2.3 Declaring and initializing variables

Variable declaration introduces a variable and its type. Initialization provides its initial value.

#include <iostream>

int main() {
    int age;          // Declaration
    age = 20;         // Assignment

    int marks = 85;   // Declaration and initialization

    std::cout << "Age: " << age << '\n';
    std::cout << "Marks: " << marks << '\n';

    return 0;
}

Output

Age: 20
Marks: 85

Notice that age is assigned a value before it is read. Reading an uninitialized local variable can cause undefined or otherwise invalid program behaviour, depending on the type and circumstances.

Variable naming rules

  • Names may contain letters, digits and underscores.

  • A name cannot begin with a digit.

  • Spaces are not allowed in identifiers.

  • C++ keywords cannot be used as ordinary variable names.

  • Identifiers are case-sensitive.

  • Descriptive names improve readability.

Valid identifiers

Invalid identifiers

studentAge

2student

total_marks

total marks

price2

float

studentName

my-name

2.4 Data types in C++

A data type determines what kind of value an object can represent and which operations can be performed on it.

C++ provides several fundamental types.

Data type

Purpose

Example

int

Integer values

int count = 10;

float

Single-precision floating-point values

float price = 10.5f;

double

Double-precision floating-point values

double pi = 3.14159;

char

Character values

char grade = 'A';

bool

Boolean values

bool isPassed = true;

void

Represents no value in certain contexts

void display();

long long

Integers with at least 64 bits of range capacity

long long population = 8000000000LL;

Exact type sizes and numeric ranges depend on the C++ implementation, except where the standard specifies minimum requirements.

Example: Using different data types

#include <iostream>
#include <string>

int main() {
    int age = 21;
    float temperature = 36.5f;
    double accountBalance = 12500.75;
    char grade = 'A';
    bool isStudent = true;
    std::string name = "Rahul";

    std::cout << "Name: " << name << '\n';
    std::cout << "Age: " << age << '\n';
    std::cout << "Temperature: " << temperature << '\n';
    std::cout << "Balance: " << accountBalance << '\n';
    std::cout << "Grade: " << grade << '\n';
    std::cout << "Is student: " << isStudent << '\n';

    return 0;
}

Output

Name: Rahul
Age: 21
Temperature: 36.5
Balance: 12500.8
Grade: A
Is student: 1

The balance appears rounded because of the default formatting of floating-point output. The Boolean value true is printed as 1 by default, and false as 0.

To use std::string, include the <string> header. A string is a standard library type, not a fundamental built-in type like int or char.

2.5 Understanding integer and floating-point types

Integer types store whole numbers, while floating-point types represent numbers that may contain fractional parts.

Integer types

Common integer types include short, int, long and long long, along with their unsigned variants.

int students = 45;
long long distance = 9000000000LL;
unsigned int items = 100;

An unsigned integer represents non-negative values within its range. Choose a type according to the values your program needs to represent.

Floating-point types

float height = 5.8f;
double percentage = 87.65;

Use double as a sensible default for many general-purpose decimal calculations. However, floating-point values have finite precision, so some decimal fractions cannot be represented exactly.

For example, financial applications often use integer minor units (such as paise) or an appropriate decimal arithmetic approach when exact monetary representation is required.

2.6 Constants in C++

A constant is a value that should not change during the relevant part of a program. In C++, const makes an object non-modifiable through that name after initialization.

Using const

#include <iostream>

int main() {
    const double PI = 3.14159;
    double radius = 5.0;

    double area = PI * radius * radius;

    std::cout << "Area: " << area << '\n';

    return 0;
}

Output

Area: 78.5397

Trying to assign a different value to PI would cause a compilation error.

Using constexpr

constexpr is used when a value or function is intended to be usable in constant expressions where the language permits it.

constexpr int DAYS_IN_WEEK = 7;
constexpr int HOURS_IN_DAY = 24;

constexpr int HOURS_IN_WEEK =
    DAYS_IN_WEEK * HOURS_IN_DAY;

Here, HOURS_IN_WEEK is a compile-time constant expression with the value 168.

Difference: const prevents modification through the declared object; constexpr additionally requires a constant-expression initializer for a variable declared this way.

2.7 Keywords and identifiers

Keywords

Keywords have reserved meanings in the C++ language. Examples include:

int, double, if, else, return, class, const, while, for and void.

They cannot be used as ordinary identifiers.

Identifiers

Identifiers are names given to variables, functions, classes and other program entities.

int studentMarks = 90;

void displayMarks() {
    // Function body
}

In this example, studentMarks and displayMarks are identifiers, while int and void are keywords.

2.8 Taking input with std::cin

The standard input stream, std::cin, allows a program to receive input from a user.

#include <iostream>

int main() {
    int age;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Your age is " << age << '\n';

    return 0;
}

Example run

Enter your age: 20
Your age is 20

The >> operator extracts input from the stream and stores the value in the variable.

Taking multiple inputs

#include <iostream>

int main() {
    int a, b;

    std::cout << "Enter two numbers: ";
    std::cin >> a >> b;

    std::cout << "Sum: " << a + b << '\n';

    return 0;
}

Example run

Enter two numbers: 10 25
Sum: 35

The user can separate the two numbers with spaces or newlines.

Practical note: This introductory example assumes valid integer input. Production programs should check whether input succeeded before using the values.

2.9 Type conversion and type casting

Type conversion changes a value from one type to another.

C++ supports implicit conversions, which the language performs automatically, and explicit conversions, which the programmer requests.

Implicit conversion

#include <iostream>

int main() {
    int number = 10;
    double result = number;

    std::cout << result << '\n';

    return 0;
}

Output

10

The integer value is converted to double when assigned to result.

A common precision mistake

int a = 5;
int b = 2;

double result = a / b;

The expression a / b performs integer division because both operands are integers. The result is 2, which is then converted to 2.0.

To perform floating-point division, convert at least one operand before division.

double result = static_cast<double>(a) / b;

The result is 2.5.

Explicit type casting

The recommended C++ style for ordinary numeric conversions is often static_cast.

int number = 10;
double converted = static_cast<double>(number);

Use explicit casts carefully: converting a floating-point value to an integer discards its fractional part, and converting a value to a type that cannot represent it may lose information or produce an out-of-range result.

2.10 Operators with variables

Variables become useful when combined with operators to perform calculations and comparisons.

Operator

Meaning

Example

+

Addition

a + b

-

Subtraction

a - b

*

Multiplication

a * b

/

Division

a / b

%

Remainder for integer operands

a % b

=

Assignment

a = 10

Example:

#include <iostream>

int main() {
    int a = 17;
    int b = 5;

    std::cout << "Addition: " << a + b << '\n';
    std::cout << "Division: " << a / b << '\n';
    std::cout << "Remainder: " << a % b << '\n';

    return 0;
}

Output

Addition: 22
Division: 3
Remainder: 2

Since both operands are integers, division produces the integer quotient 3, and the remainder operator produces 2.

2.11 Practical program: Student marks and average

This program demonstrates variable declaration, user input, arithmetic and output.

#include <iostream>
#include <iomanip>

int main() {
    double maths, science, english;

    std::cout << "Enter Maths marks: ";
    std::cin >> maths;

    std::cout << "Enter Science marks: ";
    std::cin >> science;

    std::cout << "Enter English marks: ";
    std::cin >> english;

    double total = maths + science + english;
    double average = total / 3.0;

    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Total: " << total << '\n';
    std::cout << "Average: " << average << '\n';

    return 0;
}

Example run

Enter Maths marks: 80
Enter Science marks: 90
Enter English marks: 85
Total: 255.00
Average: 85.00

How it works

  1. Three double variables store the marks.

  2. std::cin reads the user's input.

  3. The total variable stores the sum.

  4. The average variable stores the total divided by 3.0.

  5. std::fixed and std::setprecision(2) format floating-point output to two digits after the decimal point.

For a real marksheet system, you would also validate the input and check that each mark falls within the permitted range.

2.12 Common mistakes to avoid

Mistake

Problem

Correct approach

Using an uninitialized local variable

Its value is not safely available for use.

Initialize it before reading it.

Using = instead of == in a comparison

Assignment and equality comparison have different meanings.

Use the operator appropriate to the task.

Dividing two integers when a decimal is required

Integer division discards the fractional part.

Convert an operand before division.

Assigning to a const object

The assignment is not permitted.

Use a modifiable variable if the value must change.

Using float for every numeric value

The type may not provide the required precision.

Select the type based on the problem.

Using a keyword as a variable name

It violates the language's identifier rules.

Choose a valid descriptive identifier.

2.13 Hands-on exercises

Try these exercises independently. Compile and run your solutions.

Exercise 1: Personal information

Declare variables for your name, age and course. Display all three values.

Exercise 2: Basic calculator

Accept two numbers and display their sum, difference, product and quotient. Use floating-point division where appropriate.

Exercise 3: Percentage calculator

Accept marks obtained and maximum marks, then calculate the percentage. Use a suitable numeric type and avoid division by zero.

Exercise 4: Rectangle area

Declare a constant or suitable fixed value where needed, accept the length and width, and calculate the area.

Exercise 5: Debug the program

Identify and correct the errors in this code.

#include <iostream>

int main() {
    const int age = 18;
    age = 20;

    int marks = 85
    std::cout << marks / 2.0 << '\n';

    return 0;
}

2.14 Module summary

After completing this module, students should understand:

  • Variable declaration, initialization and assignment.

  • Fundamental data types and their common applications.

  • Identifiers, keywords and naming conventions.

  • Constants using const and constexpr.

  • Standard input and output with std::cin and std::cout.

  • Implicit conversions and explicit casts.

  • Integer division, floating-point division and common precision issues.

  • Practical use of variables in calculations and simple applications.

Completion criteria: Students should be able to write a small interactive C++ program that accepts input, stores values using suitable types, performs calculations and displays correctly formatted output.

2.15 Module 2 knowledge-check quiz

Which declaration creates a constant integer named MAX_SIZE with the value 100?

A. constant MAX_SIZE = 100;

B. const int MAX_SIZE = 100;

C. int const MAX_SIZE;

D. int MAX_SIZE = 100;