Why does this implicit conversion from int to uint work?

后端 未结 3 1360
再見小時候
再見小時候 2020-12-17 17:25

Using Casting null doesn't compile as inspiration, and from Eric Lippert\'s comment:

That demonstrates an interesting case. \"uint x = (int)0;\" w

3条回答
  •  孤城傲影
    2020-12-17 17:53

    The following code wil fail with the message "Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)"

    int y = 0;
    uint x = (int)y;
    

    And this will fail with: "Constant value '-1' cannot be converted to a 'uint'"

    uint x = (int)-1;
    

    So the only reason uint x = (int)0; works is because the compiler sees that 0 (or any other value > 0) is a compile time constant that can be converted into a uint

提交回复
热议问题