What is the difference between casting and coercing?

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.


Solution 1:

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

Solution 2:

Usages vary, as you note.

My personal usages are:

  • A "cast" is the usage of a cast operator. A cast operator instructs the compiler that either (1) this expression is not known to be of the given type, but I promise you that the value will be of that type at runtime; the compiler is to treat the expression as being of the given type, and the runtime will produce an error if it is not, or (2) the expression is of a different type entirely, but there is a well-known way to associate instances of the expression's type with instances of the cast-to type. The compiler is instructed to generate code that performs the conversion. The attentive reader will note that these are opposites, which I think is a neat trick.

  • A "conversion" is an operation by which a value of one type is treated as a value of another type -- usually a different type, though an "identity conversion" is still a conversion, technically speaking. The conversion may be "representation changing", like int to double, or it might be "representation preserving" like string to object. Conversions may be "implicit", which do not require a cast, or "explicit", which do require a cast.

  • A "coercion" is a representation-changing implicit conversion.