Labs ICT
Pro Login

Type Casting

Sometimes you have a value of one type but you need it to be a different type. That is where type casting comes in. C++ gives you two ways to do this — implicit casting (the compiler does it automatically) and explicit casting (you tell the compiler to do it).

Implicit Type Casting

C++ automatically converts between types when it makes sense. For example, if you assign an int to a double, C++ converts it without you asking. This is called implicit conversion. It usually works fine, but you can lose data if you go from a larger type to a smaller one without realizing it.

Explicit Type Casting

When you want to be clear about a conversion, use explicit casting. The modern C++ way is to use static_cast<type>(value). It is safe, readable, and easy to search for in your code.

#include <iostream>
using namespace std;

int main() {
  int apples = 7;
  int people = 2;

  // Integer division gives 3
  int eachInt = apples / people;
  cout << "Without casting: " << eachInt << endl;

  // Cast to double gives 3.5
  double eachDouble = static_cast<double>(apples) / people;
  cout << "With casting: " << eachDouble << endl;

  // Cast double to int truncates
  double pi = 3.14159;
  int truncated = static_cast<int>(pi);
  cout << "Truncated pi: " << truncated;
  return 0;
}

Notice that casting from double to int simply drops the decimal part. It does not round — it truncates. So 3.99 becomes 3, not 4. Keep that in mind when you convert between types.