I have been reviewing this for a long time without finding an answer, so I decide to ask: What is the difference between conversion, casting and coercion? I'm a bit clumsy with this, I really appreciate the use of a code example.
[C++] What is the difference between conversion, casting and coercion?
Conversion is the creation of a value from an expression, potentially changing the type of the resulting value.
A cast is an explicit way to convert a value. Some conversions do not require a cast. Those are called implicit conversions. Example of an implicit conversion:
int a = 42;
long b = a; // type of expression a is int,
// but implicitly converted to long
Same example using a cast to make the conversion explicit:
long b = static_cast<long>(a);
Type "coercion" is colloquially used as a synonym of conversion, but the term is not used in the specification of the C++ language. The term is used for example in the ECMAScript language (i.e. JavaScript). Example of a coercion in JS:
Number("42") + 42 // == 84
"42" + 42 // == "4242"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With