What is the difference between explicit and implicit type casts?

后端 未结 10 891
太阳男子
太阳男子 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.

    0 讨论(0)
  • 2020-12-04 18:34

    Explicit Conversions

    If a conversion cannot be made without a risk of losing information then it is an explicit conversion.

    For example -

    class ExplicitConversions
    {
        static void Main()
        {
            int x;
            double y = 6358.057;
            // Cast double to int.
            x = (int)y;
            System.Console.WriteLine(x);
        } 
    }
    

    Implicit Conversions

    If a conversion can be made without a risk of losing information then it is an implicit conversion. No special syntax is required because the conversion is type safe and no data is lost.

    For example -

    class ImplicitConversions
    {
        static void Main()
        {
            int x = 6714;
            double y;
            // Cast int to double.
            y = x;
            System.Console.WriteLine(y);
        } 
    }
    
    0 讨论(0)
  • 2020-12-04 18:35

    A simple search will give lots of informations in the net.
    difference between implicit and explicit type

    0 讨论(0)
  • 2020-12-04 18:42
    int i = 2;
    
    float a = i;        // Implicit
    float b = (float)i; // Explicit
    
    0 讨论(0)
提交回复
热议问题