What is the difference between casting and coercing?

后端 未结 7 1809
名媛妹妹
名媛妹妹 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 07:03

    According to Wikipedia,

    In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another.

    The difference between type casting and type coercion is as follows:

               TYPE CASTING           |                   TYPE COERCION
                                      |
    1. Explicit i.e., done by user    | 1. Implicit i.e., done by the compiler
                                      |
    2. Types:                         | 2. Type:
        Static (done at compile time) |     Widening (conversion to higher data 
                                      |     type)
        Dynamic (done at run time)    |     Narrowing (conversion to lower data 
                                      |     type)
                                      |
    3. Casting never changes the      | 3. Coercion can result in representation 
       the actual type of object      |    as well as type change.
       nor representation.            |
    

    Note: Casting is not conversion. It is just the process by which we treat an object type as another type. Therefore, the actual type of object, as well as the representation, is not changed during casting.

    I agree with @PedroC88's words:

    On the other hand, coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory (until the Garbage Collectors takes either away, or both).

提交回复
热议问题