What is the difference between explicit and implicit type casts?

后端 未结 10 893
太阳男子
太阳男子 2020-12-04 18:15

Can you please explain the difference between explicit and implicit type casts?

10条回答
  •  情深已故
    2020-12-04 18:30

    Explicit cast:

    int x = 0;
    float y = 3.8f;
    
    x += (int) y; //Explicit cast.
    

    This tells the compiler that the cast was intentional and that you know that the fractional part will go lost. The compiler won't complain.

    Implicit cast:

    int x = 0;
    float y = 3.8f;
    
    x += y; //Implicit cast
    

    The compiler will complain because the fractional part will be lost when converting float to int.

提交回复
热议问题