What is the difference between casting and coercing?

后端 未结 7 1754
名媛妹妹
名媛妹妹 2020-12-02 06:45

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.

7条回答
  •  独厮守ぢ
    2020-12-02 06:50

    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
    

提交回复
热议问题