C++ Type Conversion

Mon Jul 28 2025
Updated: Tue Jul 29 2025
Facebook share linkTwitter/X share linkLinkedIn share linkReddit share linkReddit share link

Sometimes data of one type needs to be used as a different type. This happens with mixed expressions in arithmetic where implicit typecasting is used to change the type of integers to floating-point to cause floating-point arithmetic to be performed, or in the statement int x = 3.5; where an implicit typecast happens to convert the 3.5 to 3 in order to then store it in the integer x.


Static Cast

Often, the programmer needs to be able to change the type of an expression of their own choosing, such as when rounding change or needing floating-point arithmetic on two integers. This is done using explicit typecasting, also called type casting or type conversion--forcibly converting a value from one data type to another through the use of a cast operator. To explicit typecast in C++ the static_cast operator is used:

static_cast<newType>(expression)

Where expression is a variable or expression to change the type of, and newType is the new type to change the expression to. This can be used to convert types between any of the simple data types except strings. For example, to convert the value 'A' to its integer value from the ASCII table, the following snippet of code could be used:

cout << static_cast<int>(‘A’) << endl;

This will cause the integer ASCII value of 'A', which is 65, to be output to the screen rather than the character 'A'

In general, for the simple data types the following is done to apply the conversion:

Start TypeConverted TypeNotes
IntegralFloating-PointAdd space for mantissa in memory
Floating-PointIntegralRemove mantissa in memory

Static Cast Usage Examples

Example 1

static_cast<int>(23.14) 23

Example 2

static_cast<double>(23) 23.0

Example 3

static_cast<double>(23) / 2 23.0 / 2 11.5

Example 4

static_cast<double>(23 / 2) static_cast<double>(11) 11.0

Example 5

static_cast<double>(23.0 / 2) static_cast<int>(11.5) 11

Example 6

static_cast<int>(23.14) * 23.0 / 2 * 9.09 23 * 23.0 / 2 * 9.09 529.0 / 2 * 9.09 264.5 * 9.09 2404.305

Example 7

static_cast<int>(23.14) * (23.0 / 2 * 9.09) static_cast<int>(23.14) * (11.5 * 9.09) static_cast<int>(23.14) * (11.5 * 9.09) static_cast<int>(23.14) * 104.535 23 * 104.535 2404.305

Example 8

static_cast<int>(23.14) * static_cast<int>(static_cast<int>(23.0 / 2) * 9.09) static_cast<int>(23.14) * static_cast<int>(static_cast<int>(11.5) * 9.09) static_cast<int>(23.14) * static_cast<int>(11 * 9.09) static_cast<int>(23.14) * static_cast<int>(99.99) 23.14 * static_cast<int>(99.99) 23 * 99 2277

Example 9

static_cast<char>(65) ‘A’

Example 10

static_cast<int>(‘A’) 65

Example 11

static_cast<char>(97) ‘a’

Example 12

static_cast<int>(‘a’) 97

Example 13

static_cast<char>(static_cast<int>(‘a’) - 32) static_cast<char>(97 - 32) static_cast<char>(65) ‘A’

Example 14

static_cast<int>(9) 57

Example 15

static_cast<char>(static_cast<int>(9) + 10) static_cast<char>(57 + 10) static_cast<char>(67) ‘C’

Static Cast Programming Example

Suppose you're writing a program to calculate how many experience points (XP) a player earns per hour while training a skill in a video game.

The player is tracked and it is found that:

  • They earned 9500xp
  • It took 37 minutes

Incorrect (without typecasting)

int xp = 9500; int minutes = 37; int hours = minutes / 60; // Because of integer division, this is 0 int xpPerHour = xp / hours; // hours being 0 causes a crash

Since the minutes are an integer when they are divided by 60 this causes integer division to be performed as 37 / 60 resulting in 0. This 0 is then used as the divisor in the following calculation which is a mathematical error resulting in a crash.

Correct (with typecasting)

int xp = 9500; int minutes = 37; int hours = static_cast<double>(minutes) / 60; // Now it's 0.6166... int xpPerHour = xp / hours;

Before calculating the hours the minutes is first cast to a double so the expression is turned into a mixed expression, forcing floating-point arithmetic to be used causing the result to be 0.6166…. The result is then used in the following calculation to calculate the proper xpPerHour of 15405.405…


String Conversions

Numerical to String

For the simple numerical data types static_cast is used to convert, but using this operator on strings does not work. For example consider the following lines of code:

string s = static_cast<string>(53); // or int i = static_cast<int>("53");

When put into a program and compiled the following errors will occur:

main.cpp:7:14: error: no matching conversion for static_cast from 'int' to 'string' (aka 'basic_string<char>') 7 | string s = static_cast<string>(53); | ^~~~~~~~~~~~~~~~~~~~~~~ main.cpp:8:11: error: static_cast from 'const char *' to 'int' is not allowed 8 | int i = static_cast<int>("53"); | ^~~~~~~~~~~~~~~~~~~~~~

This is because strings have special operators to operate on them contained in the <string> library. To convert from a numerical value to a string the to_string() function is used:

to_string(expression)

Where expression is any numerical variable or expression to be converted to a string. For example, to add 5 to 3 then concatenate the result with the string "The result is ", the following snippet of code could be used:

string s = "The result is " + to_string(5 + 3);

This will first perform the arithmetic 5 + 3 resulting in 8, then convert the result from the integer 8 to the string "8", then the string "8" will be concatenated to the end of the string "The result is " resulting in the string "The result is 8", which is then saved in the string variable s.

Since the <string> library is used for the to_string() function the library must be included with a preprocessor directive (i.e. #include <iostream>). Some other libraries do already include the <string> library though, negating the need to include the <string> library directly if using one of these other libraries already. But some libraries do not use the <string> library requiring it to be directly included. Thus to avoid confusion, and errors if a library containing the <string> library is removed from the program later, it is good practice to always include the preprocessor directive for the <string> library when using strings in a program.

String to Numerical

The <string> library provides methods to convert strings to the different numerical types. From the <string> library, the 4 typical methods needed to convert from string to numerical values are:

NameCommandDescription
String to Integerstoi(expression)Converts the expression from a string to an integer
String to Long Longstoll(expression)Converts the expression from a string to a long long
String to Floatstof(expression)Converts the expression from a string to a float
String to Doublestod(expression)Converts the expression from a string to a double

All of these functions must be passed strings that at minimum start with a number, for example:

cout << stoi("123.a") << endl;

Will output 123 as the first part of the string is able to be converted to a valid integer, the rest of the string is just tossed away in the conversion. But if the following line is used:

cout << stoi("a123") << endl;

Then at runtime the program will crash and the following error will occur:

libc++abi: terminating due to uncaught exception of type std::invalid_argument: stoi: no conversion zsh: abort ./a.out

This is because the function can not find a valid integer in the beginning of the string so the program can not continue to execute. In order to handle this error exception handling is needed which is not described until later. Thus at this point any examples needing this will not provide data to this function that will cause the program to crash.

String Conversion Usage Examples

Example 1

to_string(1.35) "1.35"

Example 2

stoi("746.34") 746

Example 3

stoll("47283756349") 47283756349

Example 4

stod("746.34")

Example 5

stoi("17.5") / 2 17 / 2 8

Example 6

stoi("17.5") / stod("2") 17 / stod("2") 17 / 2.0 17.0 / 2.0 8.5

Example 7

static_cast<int>(stoi("17.5") / stod("2")) / 2 static_cast<int>(17 / stod("2")) / 2 static_cast<int>(17 / 2.0) / 2 static_cast<int>(17.0 / 2.0) / 2 static_cast<int>(8.5) / 2 8 / 2 4

Example 8

int a = 2000, b = 277; to_string(a) + " + " + to_string(b) + " = " + to_string(a + b) to_string(a) + " + " + to_string(b) + " = " + to_string(2277) "2000" + " + " + to_string(b) + " = " + to_string(2277) "2000" + " + " + "277" + " = " + to_string(2277) "2000" + " + " + "277" + " = " + "2277" "2000 + " + "277" + " = " + "2277" "2000 + 277" + " = " + "2277" "2000 + 277 = " + "2277" "2000 + 277 = 2277"

Example 9

"Result: " + to_string(static_cast<int>(stoi("79.5173") / stod("4")) / 2) "Result: " + to_string(static_cast<int>(79 / stod("4")) / 2) "Result: " + to_string(static_cast<int>(79 / 4.0) / 2) "Result: " + to_string(static_cast<int>(79.0 / 4.0) / 2) "Result: " + to_string(static_cast<int>(19.75) / 2) "Result: " + to_string(19 / 2) "Result: " + to_string(9) "Result: " + "9" "Result: 9"

String Conversion Programming Example

You are playing a video game and fighting a monster doing damage to its health. After an attack the damage the attack deals and the updated health of the monster need to be displayed. To keep track of the health/damage and do the arithmetic integers are used, but to display the damage/health strings are needed.

Suppose the Monster has 100 health, the player can at maximum hit 20 damage on the monster, and when the player attacks a random number is generated choosing the player does 75% of the maximum damage to the monster. Apply the damage to the monster's health, prepare a message as a string to display how much damage is applied and how much health the monster has before and after taking the damage, then output the 3 messages to the terminal.

First, create a program with variables for the monster's health, max damage, and percent of max damage taken. Then, create a message of how much health the monster has prior to taking damage using the monster's health:

#include <string> using namespace std; int main() { int monsterHealth = 100, maxDamage = 20; double percent = 0.75; string priorMsg = "Monster's Health (w/o dmg): " + to_string(monsterHealth); return 0; }

The monsterHealth is stored in an integer so arithmetic can be performed on it, but this causes issues when trying to create the message of how much health the monster has because there is no + operation between a string and an integer in C++. Thus, the integer must be converted to a string first so the string version of the integer can be concatenated to the end of the rest of the message.

Next, the damage can be calculated and an appropriate message created:

int main() { int monsterHealth = 100, maxDamage = 20; double percent = 0.75; string priorMsg = "Monster's Health (w/o dmg): " + to_string(monsterHealth); string dmgMsg = to_string(static_cast<int>(maxDamage * percent)) + " damage done"; return 0; }

The maxDamage is multiplied by the percent to get the amount of damage done to the monster, but this results in a floating point value, but video game health generally uses integers. Rather than try and round the value to the nearest whole number, the mantissa can just be removed by converting the value to an integer using the static_cast this integer value is then converted to a string so it can be concatenated with the rest of the message.

Last, the damage can be subtracted from the monster's health, a message of how much updated health the monster has can be created, and all 3 messages can be output to the terminal:

int main() { int monsterHealth = 100, maxDamage = 20; double percent = 0.75; string priorMsg = "Monster's Health (w/o dmg): " + to_string(monsterHealth); string dmgMsg = to_string(static_cast<int>(maxDamage * percent)) + " damage done"; monsterHealth -= static_cast<int>(maxDamage * percent); string afterMsg = "Monster's Heath (w/ dmg): " + to_string(monsterHealth); cout << priorMsg << endl << dmgMsg << endl << afterMsg << endl; return 0; }

The static_cast is used to make sure any mantissa is thrown away so that a small mantissa doesn't cause an extra health point to be taken away from the monster. The updated health can then be passed again to the to_string() function to convert it to a string so it can be concatenated with the rest of the message. The messages are then output to the terminal.

A simplified version:

int main() { int monsterHealth = 100, maxDamage = 20; double percent = 0.75; string priorMsg = "Monster's Health (w/o dmg): " + to_string(monsterHealth); int damage = maxDamage * percent; string dmgMsg = to_string(damage) + " damage done"; monsterHealth -= damage; string afterMsg = "Monster's Heath (w/ dmg): " + to_string(monsterHealth); cout << priorMsg << endl << dmgMsg << endl << afterMsg << endl; return 0; }

This is optimized by only calculating the damage once, which will still cause a floating-point result from the maxDamage * percent, but this time saving the floating-point value into an integer variable causes an implicit typecast to happen. This causes the mantissa of the damage to be removed leaving only the integer part which is stored in the damage variable. The value is then used to subtract from the monster's health and create the message rather than doing the calculations in-line.


Terms

  1. Explicit Typecast - forcibly converting a value from one data type to another through the use of a cast operator.

Questions

Implicit vs Explicit Conversion

  1. What kind of conversion happens in the following code? double x = 5;

  2. Rewrite the following line using an explicit cast: float f = 10;

  3. Given int i = 3.9;, what value is stored in i? Is this implicit or explicit?

  4. Why is this better style? int a = static_cast<int>(3.9); instead of int a = 3.9;

Basic static_cast Conversions

  1. What is the result of static_cast<int>(4.9)?

  2. What is the result of static_cast<double>(3)?

  3. What is the result of static_cast<char>(65)?

  4. What is the result of static_cast<int>('B')?

  5. What is the result of static_cast<float>(10)?

  6. What is the result of static_cast<int>(3.99999)?

  7. What is the result of static_cast<double>('C')?

  8. What is the result of static_cast<int>(2.999)?

  9. What is the result of static_cast<char>(97)?

  10. What is the result of static_cast<int>(-3.8)?

  11. What is the result of static_cast<int>(static_cast<float>(4.2))?

  12. What is the result of static_cast<double>(static_cast<int>(9.99))?

  13. What is the result of static_cast<int>(static_cast<char>(57))?

Static Cast with Simple Arithmetic

  1. What is the result of static_cast<int>(5.6) + 2?

  2. What is the result of static_cast<double>(3) + 0.14?

  3. What is the result of static_cast<char>(66 + 1)?

  4. What is the result of static_cast<int>(3.8 + 2.2)?

  5. What is the result of static_cast<int>(3.8) + static_cast<int>(2.2)?

  6. What is the result of static_cast<float>(3 + 7 / 2)?

  7. What is the result of static_cast<int>(2.5) + 4?

  8. What is the result of 5 + static_cast<int>(6.7)?

  9. What is the result of static_cast<int>(3.14) - 1?

  10. What is the result of static_cast<double>(7) + 1.1?

  11. What is the result of static_cast<int>('A') + 1?

Static Cast with Mixed Arithmetic

  1. What is the result of static_cast<double>(5 / 2)?

  2. What is the result of 5 / static_cast<double>(2)?

  3. What is the result of static_cast<int>(3.5 * 2.0)?

  4. What is the result of static_cast<int>(9.0) / 2?

  5. What is the result of static_cast<float>(10 % 3)?

  6. What is the result of static_cast<int>(10.0) % 3?

  7. What is the result of static_cast<int>(7.2) * 2?

  8. What is the result of static_cast<int>(9.9) / 3?

  9. What is the result of 10 / static_cast<double>(3)?

  10. What is the result of static_cast<double>(10 / 3)?

  11. What is the result of static_cast<int>(10.0 / 3.0)?

  12. What is the result of static_cast<int>(8.5) % 3?

  13. What is the result of static_cast<int>(10.0 / 3)?

Challenging Arithmetic Expressions with Static Casts

  1. What is the result of static_cast<int>(5.7) + static_cast<int>(2.9) * 2?

  2. What is the result of (static_cast<double>(3) + 4) / 2?

  3. What is the result of static_cast<int>((5 + 3.9) * 2)?

  4. What is the result of static_cast<int>(5 + 3.9 * 2)?

  5. What is the result of static_cast<int>(10.0 / 4) * 2 + 1?

  6. What is the result of static_cast<int>(10.0) / static_cast<int>(3.0)?

  7. What is the result of static_cast<int>(5.8) + static_cast<int>(2.1) * static_cast<int>(3.6)?

  8. What is the result of (static_cast<double>(3) + 4.5) / 2?

  9. What is the result of static_cast<int>((4.9 + 2.1) * 2)?

  10. What is the result of static_cast<int>(3.0) + static_cast<int>(2.0 * 3.5)?

  11. What is the result of static_cast<int>((3 + 2.5) / 2)?

  12. What is the result of static_cast<int>(3 + 2.5 / 2)?

  13. What is the result of static_cast<int>((3 + 2.5) % 2)?

  14. What is the result of static_cast<int>(static_cast<double>(5) / 2)?

  15. What is the result of static_cast<double>(static_cast<int>(7.6 + 1.3))?

  16. What is the result of static_cast<int>((2.0 + 3) * 2.5)?

  17. What is the result of static_cast<int>(2.0 + 3 * 2.5)?

  18. What is the result of static_cast<int>(2.5 * static_cast<int>(3.99))?

Basic String Conversions

  1. What is the result of to_string(42)?

  2. What is the result of to_string(3.14)?

  3. What is the result of stoi("123")?

  4. What is the result of stod("45.67")?

  5. What happens if you run stoi("abc123")?

  6. What happens if you run stod("12.3abc")?

  7. What is the result of to_string(static_cast<int>(4.7))?

Complex String Conversions

  1. What is the result of stoi("4.75") / stod("2")?

  2. What is the result of stoi("5.75") / stoi("2.25asdf")

  3. What is the result of stod("10.5abc") / stoi("2")?

  4. What is the result of static_cast<int>(stod("3.99abc")) + stoi("4.5xyz")?

  5. What happens when you run stoi("one hundred") + 5?

  6. What is the result of stoi("50.0") + static_cast<int>(stod("25.7"))?

  7. What is the result of stoi("9.99") * static_cast<int>(stod("1.1"))?

  8. What is the result of static_cast<int>(stod("7.5")) + stoi("abc8")?

  9. What is the result of stoi("12.0") / static_cast<int>(stod("3.0abc"))?

  10. What is the result of stoi("42") + static_cast<int>(stod("2.71828xyz"))?

Errors

  1. What is wrong with the following code? Fix it.
int a = 5.7; cout << a << endl;
  1. Why does this fail to compile? Fix it.
int a = static_cast<int>("5.7");
  1. Why does this fail to compile? Fix it.
char c = static_cast<char>("A");
  1. The following code compiles but produces an incorrect result. Why? Fix it.
int x = 10; int y = 3; double result = static_cast<double>(x / y);
  1. What's wrong with this percentage calculator? Fix the error in conversion.
int total = 10; int correct = 3; cout << "Total points: "; cin >> total; cout << "Correct points: "; cin >> correct; double percent = static_cast<double>(correct / total) * 100;
  1. What's wrong with this code? Fix it.
double x = 9.7; string s = static_cast<string>(x);
  1. Identify the error and correct it.
string x = "42"; int y = static_cast<int>(x);
  1. This code compiles but crashes. Why? Fix it.
string input = "abc"; int x = stoi(input) + 5;
  1. This code intends to convert a string to a float. Fix the error.
string s = "3.14"; int f = stof(s);
    1. Why is this conversion incorrect? Fix it.
string s = "1234567890123456789"; int val = stoi(s);
  1. What's wrong with this code? Fix it.
double d = 5.5; long long x = stoll(d);
  1. Why won’t this compile?
string str = "15"; float f = static_cast<float>(str); `` 90. What's wrong with this code? Fix it. ```cpp string a = "hello"; string b = to_string(a);
  1. Fix the implicit conversion logic in this example.
string number = "100"; cout << static_cast<string>(stoi(number)) + " apples" << endl;

Programming Questions

  1. Write a C++ statement that stores the result of dividing 5 by 2 as a double using static_cast.

  2. Given double pi = 3.14159, write a C++ statement that prints only the integer part using static_cast.

  3. Write a program that converts a user-entered character to its ASCII value using static_cast.

  4. Write a program that takes two user-entered double values and prints their integer product using static_cast.

  5. Write a program that simulates integer division and modulus of two user-entered double numbers by casting both to int first.

  6. Write a program that takes a user-entered number of seconds (as a double) and prints the number of whole minutes by dividing the amount of seconds by 60 and using static_cast.

  7. Write a program that takes a user-entered weight of an object in kilograms (as a double) and prints the integer number of pounds by multiplying the kilograms by 2.205 and using and static_cast.

  8. Write a program that takes a user-entered temperature in Fahrenheit (as a double), converts it to Celsius, casts both of the temperatures to an int, and then concatenates the two converted values to the string X°F is Y°C where X is the converted temp in Fahrenheit and Y is the converted temp in Celsius. The string should then be printed.

  9. Write a program that takes a user-entered birth year as a string, converts it to an int, calculates their age using the current year, concatenates the age to the string You are X years old where X is the calculated age, and prints the string.

  10. Write a program that takes a floating point bill amount and prints how many whole dollars the person should pay, and how much change the person would receive.

  11. Write a program that asks the user to enter a dollar amount as a string (e.g. "4.25"), then converts it to a number, multiplies by 100, and displays the number of pennies as an integer. Use stod, static_cast, and/or to_string.

  12. Ask the user for their age as a string (e.g., "20"). Convert it to an int, calculate an approximate number of seconds they’ve been alive (use 365.25 days/year), and print it as a string.

  13. A GPS sensor returns elevation as a string in feet: "5450". Convert it to meters (multiply by 0.3048), round to the nearest meter using static_cast<int>(), and print the result.

  14. You're building a simple user profile link. The user enters their ID number as an int, and you need to create a URL like "https://myapp.com/user/ID" where ID is the id entered. Write a program that reads in the ID as an int, concatenates the ID to the link string, then outputs the link.