Type Casting in C++

Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can typecast long to int.

Type casting operators allow you to convert a datum of a given type to another.

There are several ways to do this in C++.

The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):

int i; 
float f = 3.14;
i = (int) f;

The previous code converts the float number 3.14 to an integer value (3), the remainder is lost.

Here, the typecasting operator was (int).

Another way to do the same thing in C++ is using the functional notation:

preceding the expression to be converted by the type and enclosing the expression between parentheses:

i = int ( f );

Both ways of type casting are valid in C++.

sizeof()

This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object:

a = sizeof (char);

This will assign the value 1to a because charis a one-byte long type.

The value returned by sizeofis a constant, so it is always determined before program execution.

Other operators

Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming. Each one is treated in its respective section.

// Type Casting
#include <iostream>
using namespace std;

int main(){
  int i; 
  float f = 3.14;
  i = (int) f; 

  cout<< i;
  cout<< f;

  return 0;
}

The output of the code above will be: 3 3.14 because the value of f is typecasted to an integer value and stored in variable i.

The value of f is not changed.

The sizeof operator is used to determine the size of a variable or data type.

Now that you have learned about how Type Casting work with C++ programming. Lets learn something about Preceding of Operators in C++ in the next section.