Lesson 13 of 60 – Type Casting in C++
22%

Type Casting in C++

Type casting means converting a value from one data type to another. C++ provides several ways to perform type conversions, including implicit conversion and explicit casts.

Note: Be careful when converting between numeric types because some conversions can lose information, such as the fractional part of a decimal value.

1. What is Type Casting?

Type casting is the process of converting a value from one data type to another data type.

double price = 99.50;
int value = static_cast<int>(price);

Here, the double value is explicitly converted to an int.

2. Why Do We Need Type Casting?

Type conversion is useful when different data types need to work together in an expression or when a specific type is required.

  • Convert integer values to decimal values
  • Convert decimal values to integers
  • Control the type used in calculations
  • Convert character values to numeric values
  • Make conversions explicit and readable

3. Implicit Type Conversion

Implicit conversion happens automatically when C++ converts a value to another compatible type.

int number = 10;
double result = number;

The integer value is automatically converted to a double when it is assigned to result.

4. Automatic Conversion Example

#include <iostream>

int main() {

    int number = 10;
    double value = number;

    std::cout << value;

    return 0;
}

The conversion from int to double happens automatically.

5. Integer to Double

An integer can be converted to a floating-point type.

int marks = 85;

double result = marks;

The value 85 becomes a double value suitable for floating-point calculations.

6. Double to Integer

A decimal value can be converted to an integer, but the fractional part is discarded.

double price = 99.75;

int value = static_cast<int>(price);

The value stored in value is 99.

7. Explicit Type Conversion

Explicit conversion means that the programmer directly specifies the desired type.

double price = 99.75;

int value = static_cast<int>(price);

The static_cast expression clearly shows the intended conversion.

8. static_cast

static_cast is the most common C++ cast for straightforward compile-time conversions between compatible types.

int number = 10;

double result = static_cast<double>(number);

Here, number is explicitly converted to double.

9. Integer Division Problem

When two integers are divided, the result is integer division.

int a = 5;
int b = 2;

int result = a / b;

The result is 2, not 2.5.

10. Fixing Integer Division

You can convert one operand to a floating-point type before division.

int a = 5;
int b = 2;

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

Now the result is 2.5.

11. Casting Both Operands

It is usually enough to convert one operand because the other operand will then be converted as part of the arithmetic operation.

int a = 5;
int b = 2;

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

The result is 2.5.

12. C-Style Cast

C-style casts can also be used in C++, although modern C++ generally prefers named casts because they make the intended conversion clearer.

double price = 99.75;

int value = (int)price;

For modern C++ code, static_cast<int>(price) is generally clearer.

13. static_cast Syntax

The basic syntax of static_cast is:

static_cast<target_type>(value)

Example:

int number = 25;

double value = static_cast<double>(number);

14. Character to Integer

A character can be converted to an integer type. The result represents the character's numeric code value in the execution character set.

char ch = 'A';

int code = static_cast<int>(ch);

std::cout << code;

The exact numeric code is determined by the character set used by the implementation.

15. Integer to Character

An integer can also be explicitly converted to char.

int code = 65;

char ch = static_cast<char>(code);

std::cout << ch;

The displayed character depends on the execution character set.

16. Float to Integer

A floating-point value can be converted to an integer.

float price = 45.89f;

int value = static_cast<int>(price);

The fractional part is discarded during this conversion.

17. Integer to Float

An integer can be explicitly converted to a floating-point type.

int marks = 90;

float result = static_cast<float>(marks);

18. Double to Float

A double can be converted to a float.

double price = 99.987654;

float value = static_cast<float>(price);

This conversion may lose precision because float commonly has less precision than double.

19. Bool to Integer

A Boolean value can be converted to an integer.

bool passed = true;

int value = static_cast<int>(passed);

A true value converts to 1 and false converts to 0.

20. Integer to Bool

An integer can be converted to bool.

int number = 10;

bool result = static_cast<bool>(number);

Zero converts to false, while a non-zero value converts to true.

21. Type Casting in Calculations

Type casting can be useful when a calculation requires a particular numeric type.

int totalMarks = 450;
int subjects = 5;

double average =
    static_cast<double>(totalMarks) / subjects;

std::cout << average;

The result is calculated as a floating-point value.

22. Narrowing Conversion

A narrowing conversion can cause information to be lost. For example, converting a decimal value to an integer removes its fractional part.

double number = 25.75;

int result = static_cast<int>(number);

The value stored in result is 25.

23. Type Casting with Variables

#include <iostream>

int main() {

    int marks = 85;

    double percentage =
        static_cast<double>(marks);

    std::cout << percentage;

    return 0;
}

The integer value is explicitly converted to a double value.

24. Type Casting with User Input

#include <iostream>

int main() {

    int total;
    int students;

    std::cout << "Enter total marks: ";
    std::cin >> total;

    std::cout << "Enter number of students: ";
    std::cin >> students;

    double average =
        static_cast<double>(total) / students;

    std::cout << "Average: " << average;

    return 0;
}

25. Implicit vs Explicit Conversion

Implicit Conversion Explicit Conversion
Performed automatically Requested directly by the programmer
double x = 10; double x = static_cast<double>(10);
Less visible in source code Clearly communicates the intended conversion

26. Common Type Casting Mistakes

  • Forgetting that integer division discards the fractional part.
  • Converting decimal values to integers without considering information loss.
  • Assuming every type conversion is lossless.
  • Using a cast when the correct type could be used directly.
  • Using unclear C-style casts when a named C++ cast communicates the intention better.

27. Type Casting Example with Marks

#include <iostream>

int main() {

    int obtained = 425;
    int total = 500;

    double percentage =
        static_cast<double>(obtained) /
        total * 100;

    std::cout << "Percentage = "
              << percentage;

    return 0;
}

Casting one operand to double ensures that the division is performed using floating-point arithmetic.

28. Complete Type Casting Example

#include <iostream>

int main() {

    int a = 10;
    int b = 3;

    int integerResult = a / b;

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

    std::cout << "Integer Result: "
              << integerResult << std::endl;

    std::cout << "Decimal Result: "
              << decimalResult << std::endl;

    return 0;
}

The first division uses integer arithmetic, while the second explicitly converts one operand to double.

29. C++ Cast Operators

C++ provides several named cast operators for different situations:

  • static_cast – common conversions checked primarily at compile time.
  • dynamic_cast – checked conversions for certain polymorphic class hierarchies.
  • const_cast – changes const or volatile qualification.
  • reinterpret_cast – performs low-level reinterpretation of values.

For beginner-level numeric conversions, static_cast is the most commonly encountered named cast.

30. Type Casting – Final Summary

Concept Example
Implicit conversion double x = 10;
Explicit conversion double x = static_cast<double>(10);
Double to int int x = static_cast<int>(10.5);
Int to double double x = static_cast<double>(10);
Integer division 5 / 2 gives 2
Floating-point division static_cast<double>(5) / 2 gives 2.5

📌 Key Points

  • Type casting means converting a value from one type to another.
  • Implicit conversion is performed automatically by the language.
  • Explicit conversion is requested directly by the programmer.
  • static_cast is commonly used for straightforward numeric conversions.
  • Converting an integer to a floating-point type can preserve fractional calculations.
  • Converting a floating-point value to an integer discards its fractional part.
  • Integer division can produce an integer result even when a decimal result is expected.
  • Converting one operand to double can produce floating-point division.
  • Some conversions can cause loss of information or precision.
  • C++ also provides dynamic_cast, const_cast, and reinterpret_cast for specialized situations.

🧠 Quick Quiz

Question: Which C++ cast is commonly used for straightforward explicit numeric conversions?