Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between conversion, casting and coercion?

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.

like image 498
danielm2402 Avatar asked Oct 20 '25 13:10

danielm2402


1 Answers

[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"
    
like image 160
eerorika Avatar answered Oct 22 '25 03:10

eerorika