zoukankan      html  css  js  c++  java
  • checked和unchecked的区别

    int类型的最大值是2147483647,2个最大值相加就会超出int的最大值,即出现溢出。

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                int y = 2147483647;
    
                int x = 2147483647;
    
                int z = x + y;
    
                Console.WriteLine(z.ToString());
    
                Console.ReadKey();
    
            }
    
        }
    

    把断点打在 int z = x + y;代码行,单步调试,可以看到z的值为-2。因为int类型的最大值是2147483647,x + y超出了最大值,出现了溢出。
    1

    □ 使用checked

    如果我们想让编译器帮我们判断是否溢出,就使用checked关键字。

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                int y = 2147483647;
    
                int x = 2147483647;
    
                int z = checked(x + y);
    
            }
    
        }

    运行,抛出溢出异常:   
    2

    如果我们想手动捕获并打印异常,应该这样写:

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                int y = 2147483647;
    
                int x = 2147483647;
    
                try
    
                {
    
                    int z = checked(x + y);
    
                }
    
                catch (OverflowException ex)
    
                {
    
                    Console.WriteLine(ex.Message);
    
                }
    
                Console.ReadKey();
    
            }
    
        }
    

    运行,
    3

    □ 使用unchecked   

    使用unchecked不会抛出溢出异常。

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                int y = 2147483647;
    
                int x = 2147483647;
    
                int z = unchecked(x + y);
    
                Console.WriteLine(z.ToString());
    
                Console.ReadKey();
    
            }
    
        }
    

    结果为:-2

    总结:checked关键字用来检查、捕获溢出异常,unchecked关键字用来忽略溢出异常。

  • 相关阅读:
    入门菜鸟
    FZU 1202
    XMU 1246
    Codeforces 294E Shaass the Great 树形dp
    Codeforces 773D Perishable Roads 最短路 (看题解)
    Codeforces 814E An unavoidable detour for home dp
    Codeforces 567E President and Roads 最短路 + tarjan求桥
    Codeforces 567F Mausoleum dp
    Codeforces 908G New Year and Original Order 数位dp
    Codeforces 813D Two Melodies dp
  • 原文地址:https://www.cnblogs.com/darrenji/p/3907782.html
Copyright © 2011-2022 走看看