Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers C++ Memory Management

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion C++ Lambda

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Friend Functions C++ Inheritance C++ Polymorphism C++ Templates C++ Files C++ Date

C++ Errors

C++ Errors C++ Debugging C++ Exceptions C++ Input Validation

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ Namespaces

C++ Namespaces

C++ Projects

C++ Projects

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Syllabus C++ Study Plan C++ Certificate


C++ Type Conversion


Type Conversion

Sometimes, you have to convert the value of one data type to another type. This is known as type conversion.

For example, if you try to divide two integers, 5 by 2, you might expect the result to be 2.5. But since we are working with integers (and not floating-point values), the following example will just output 2:

Example

#include <iostream>
using namespace std;

int main() {
  int x = 5;
  int y = 2;
  int result = x / y;

  cout << result; // Outputs 2
  return 0;
}
Try it Yourself »

To get the right result, you need to know how type conversion works.

There are two types of conversion in C++:

  • Implicit Conversion (automatically)
  • Explicit Conversion (manually)

Implicit Conversion

Implicit conversion is done automatically by the compiler when you mix types in an expression or assign a value of one type to another.

For example, assigning an int to a double:

Example

#include <iostream>
using namespace std;

int main() {
  double myDouble = 9;   // Automatic conversion: int to double
  cout << myDouble;      // 9
  return 0;
}
Try it Yourself »

Be careful with implicit conversion in the other direction, which may truncate the value (the decimal part is lost):

Example

#include <iostream>
using namespace std;

int main() {
  int myInt = 9.99;  // Automatic conversion: double to int (truncates)
  cout << myInt;     // 9
  return 0;
}
Try it Yourself »

As for integer division, even if the result is stored in a floating-point variable, dividing two integers still performs integer division first:

Example

#include <iostream>
using namespace std;

int main() {
  double sum = 5 / 2; // both operands are int, so 5/2 == 2
  cout << sum;        // 2
  return 0;
}
Try it Yourself »

To get a floating-point result, at least one operand must be floating-point.


Explicit Conversion

Explicit conversion is done manually. In C++ you should prefer the static_cast<> operator because it is clear and type-safe.

Example: make one operand double

#include <iostream>
using namespace std;

int main() {
  double sum = static_cast<double>(5) / 2; // 5.0 / 2 == 2.5
  cout << sum; // 2.5
  return 0;
}
Try it Yourself »

You can also cast a variable:

Example: cast a variable

#include <iostream>
using namespace std;

int main() {
  int num1 = 5;
  int num2 = 2;
  double sum = static_cast<double>(num1) / num2;
  cout << sum; // 2.5
  return 0;
}
Try it Yourself »

If you want to control the number of decimals in the output, use iostream formatting:

Example: control decimal precision

#include <iostream>
#include <iomanip>   // for fixed and setprecision
using namespace std;

int main() {
  int num1 = 5;
  int num2 = 2;
  double sum = static_cast<double>(num1) / num2;

  cout << fixed << setprecision(1) << sum; // 2.5
  return 0;
}
Try it Yourself »

C-Style Cast vs C++ Casts

You may also see the C-style cast syntax, for example (double)num1. It works, but modern C++ encourages using static_cast<> because it is clearer and helps the compiler find mistakes.

Example: C-style cast (works, but less explicit)

#include <iostream>
using namespace std;

int main() {
  int a = 7, b = 4;
  double q = (double)a / b; // 1.75
  cout << q;
  return 0;
}
Try it Yourself »

Tip: Prefer static_cast<> for ordinary numeric conversions. It documents your intent and is safer than a C-style cast.


Summary

  • Implicit conversion happens automatically (for example, assigning an int to a double).
  • Integer division with two integers discards the fractional part. Make one operand floating-point to get a fractional result.
  • Use static_cast<> for explicit, clear, and safer conversions in C++.

Real-Life Example

Here’s a real-life example of type conversion where we create a program to calculate the percentage of a user's score in relation to the maximum score in a game:

Example

#include <iostream>
#include <iomanip> // for setprecision
using namespace std;

int main() {
  // Set the maximum possible score in the game to 500
  int maxScore = 500;

  // The actual score of the user
  int userScore = 423;

  /* 
     Calculate the percentage of the user's score in relation to 
     the maximum available score.
     Convert userScore to double to make sure the division is accurate.
  */
  double percentage = static_cast<double>(userScore) / maxScore * 100.0;

  // Print the percentage with 2 decimal places
  cout << fixed << setprecision(2);
  cout << "User's percentage is " << percentage << "%" << endl;

  return 0;
}
Try it Yourself »

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.