Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between casting and coercing?

Tags:

c#

oop

I've seen both terms be used almost interchangeably in various online explanations, and most text books I've consulted are also not entirely clear about the distinction.

Is there perhaps a clear and simple way of explaining the difference that you guys know of?

Type conversion (also sometimes known as type cast)

To use a value of one type in a context that expects another.

Nonconverting type cast (sometimes known as type pun)

A change that does not alter the underlying bits.

Coercion

Process by which a compiler automatically converts a value of one type into a value of another type when that second type is required by the surrounding context.

like image 283
Alexandr Kurilin Avatar asked Jan 13 '12 21:01

Alexandr Kurilin


People also ask

What is the difference between type casting and coercion?

In typing casting, the destination data type may be smaller than the source data type, when converting the data type to another data type. Whereas in type conversion, the destination data type can't be smaller than source data type.

What is casting example?

Casting materials are usually metals or various time setting materials that cure after mixing two or more components together; examples are epoxy, concrete, plaster and clay. Casting is most often used for making complex shapes that would be otherwise difficult or uneconomical to make by other methods.

What are the different types of conversion?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting.

What is type coercion in Python?

Many programming languages have something called type coercion; it's where the language will implicitly convert one object to another type of object in certain circumstances. Python does not have type coercion.


1 Answers

Type Conversion:

The word conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer.

The word coercion is used to denote an implicit conversion.

The word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretation of a bit-pattern or a real conversion.

So, coercion is implicit, cast is explicit, and conversion is any of them.


Few examples (from the same source) :

Coercion (implicit):

double  d; int     i; if (d > i)      d = i; 

Cast (explicit):

double da = 3.3; double db = 3.3; double dc = 3.4; int result = (int)da + (int)db + (int)dc; //result == 9 
like image 162
Igor Avatar answered Sep 19 '22 17:09

Igor