代码之家  ›  专栏  ›  技术社区  ›  dreadwail

处理C中整数溢出的最佳方法?

  •  38
  • dreadwail  · 技术社区  · 14 年前

    处理整数溢出是一项常见的任务,但是用C语言处理它的最佳方法是什么?有没有比其他语言更简单的句法?或者这真的是最好的方法?

    int x = foo();
    int test = x * common;
    if(test / common != x)
        Console.WriteLine("oh noes!");
    else
        Console.WriteLine("safe!");
    
    6 回复  |  直到 7 年前
        1
  •  96
  •   Wollmich    7 年前

    我不需要经常用这个,但是你可以用 checked 关键词:

    int x = foo();
    int test = checked(x * common);
    

    如果溢出,将导致运行时异常。来自MSDN:

    在选中的上下文中,如果表达式生成的值 在目标类型的范围之外,结果取决于 表达式是常量还是非常量。常数 表达式导致编译时错误,而非常量表达式 在运行时评估并引发异常。

    我还应该指出还有另一个C关键字, unchecked ,这当然与 checked 忽略溢出。你可能想知道你什么时候用过 未检查的 因为它似乎是默认行为。好吧,有一个C编译器选项,它定义了表达式在 选中的 未检查的 处理: /checked . 可以在项目的高级生成设置下进行设置。

    如果有很多表达式需要检查,最简单的方法就是设置 /checked 建立选项。然后任何溢出的表达式,除非 未检查的 ,将导致运行时异常。

        2
  •  18
  •   JaredPar    14 年前

    尝试以下操作

    int x = foo();
    try {
      int test = checked (x * common);
      Console.WriteLine("safe!");
    } catch (OverflowException) {
      Console.WriteLine("oh noes!");
    }
    
        3
  •  7
  •   Henrik    8 年前

    最好的方法是如micheal所说-使用选中的关键字。 可以这样做:

    int x = int.MaxValue;
    try   
    {
        checked
        {
            int test = x * 2;
            Console.WriteLine("No Overflow!");
        }
    }
    catch (OverflowException ex)
    {
       Console.WriteLine("Overflow Exception caught as: " + ex.ToString());
    }
    
        4
  •  4
  •   Alon Gubkin    14 年前

    有时, 最简单的 方式是 最好的 方式。我想不出一个更好的方法来写你写的东西,但是你可以把它简写为:

    int x = foo();
    
    if ((x * common) / common != x)
        Console.WriteLine("oh noes!");
    else
        Console.WriteLine("safe!");
    

    注意我没有移除 x 变量,因为调用 foo() 三次。

        5
  •  1
  •   YourUncleBob    10 年前

    旧线,但我刚碰到这个。我不想使用例外。我最后得到的是:

    long a = (long)b * (long)c;
    if(a>int.MaxValue || a<int.MinValue)
        do whatever you want with the overflow
    return((int)a);
    
        6
  •  0
  •   Jesse Williams    8 年前

    所以,我在这个事实之后遇到了这个问题,它基本上回答了我的问题,但是对于我的特殊情况(如果其他人也有同样的要求),我想要任何超过有符号int的正值的东西来解决这个问题。 int.MaxValue :

    int x = int.MaxValue - 3;
    int someval = foo();
    
    try
    {
       x += someval;
    }
    
    catch (OverflowException)
    {
       x = int.MaxValue;
    }