Type Casting

Explicitly converts data types.

 

Syntax:  (target_data_type)identifier ;

 

#include <iostream>
using namespace std ;

int main () {

	int myInt = 42 ;
	int yourInt = 17 ;
	int divInt = myInt / yourInt ;

	cout << "42 / 17 WITHOUT type casting: "<< divInt << endl ;

	//typecast myInt to a float
	float divFlo = (float)myInt / yourInt ;
	cout << "42 / 17 WITH type casting: "<< divFlo << endl ;

	return 0;
}

Compile & run:

42 / 17 WITHOUT type casting: 2
42 / 17 WITH type casting: 2.47059

Leave a Reply