What is the difference between explicit and implicit type casts?

Viewed 46700

Can you please explain the difference between explicit and implicit type casts?

11 Answers

Type Casting: Conversion of one data type to another data type. and it can be done in two ways.

Implicit Type Casting, Explicit Type Casting

Implicit type casting is performed by the compiler on its own when it encounters a mixed data type expression in the program. it is also known as automatic conversion as it is done by the compiler without the programmer’s assistance. implicit casting doesn’t require a casting operator.

Example:-

int a=42;
float b=a;

here b will contain typecast value of a, because while assigning value to b compiler typecasts the value of an into float then assigns it to b.

Explicit type casting is performed by the programmer. In this typecasting programmer tells the compiler to typecast one data type to another data type using type casting operator. but there is some risk of information loss is there, so one needs to be careful while doing it

Example:-

float a=42.12;
int b=(int)a;

here we explicitly converted float value of a to int while assigning it to int b. (int) is the typecasting operator with the type in which you wants to convert.

Explicit from MSDN -

If a conversion operation can cause exceptions or lose information, you should mark it explicit. This prevents the compiler from silently invoking the conversion operation with possibly unforeseen consequences.

Implicit from MSDN -

if the conversion is guaranteed not to cause a loss of data

From a general point of view; here is the diff between the two type of Casts :

Implicit type casting is performed by the compiler on its own when it encounters a mixed data type expression in the program. it is also known as automatic conversion as it is done by compiler without programmer’s assistance. implicit casting doesn’t require a casting operator.

Explicit type casting is performed by the programmer. In this type casting programmer tells compiler to type cast one data type to another data type using type casting operator. but there is some risk of information loss is there, so one needs to be careful while doing it.

you can refer to This article for more details.

Related