一元减并签署对无符号的转换 [英] Unary minus and signed-to-unsigned conversion

查看:115
本文介绍了一元减并签署对无符号的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是始终技术上是正确的:

Is this always technically correct:

unsigned abs(int n)
{
    if (n >= 0) {
        return n;
    } else {
        return -n;
    }
}

在我看来,这里如果-INT_MIN> INT_MAX,以-nEX pression可能溢出,当n == INT_MIN,因为-INT_MIN是边界之外。但在我的编译器这似乎工作确定...这是一个实现细节或可依靠的行为?

It seems to me that here if -INT_MIN > INT_MAX, the "-n" expression could overflow when n == INT_MIN, since -INT_MIN is outside the bounds. But on my compiler this seems to work ok... is this an implementation detail or a behaviour that can be relied upon?

加长版

上下文的一点:我写了GMP整数类型(mpz_t)一个C ++包装,并采取灵感现有GMP的C ++封装(称为mpz_class)。当处理除了mpz_t与符号的整数有code是这样的:

A bit of context: I'm writing a C++ wrapper for the GMP integer type (mpz_t) and taking inspiration for the existing GMP C++ wrapper (called mpz_class). When handling addition of mpz_t with signed integers there is code like this:

static void eval(mpz_ptr z, signed long int l, mpz_srcptr w)
{
  if (l >= 0)
    mpz_add_ui(z, w, l);
  else
    mpz_sub_ui(z, w, -l);
}

在换句话说,如果有符号整数为正时,使用无符号相加的常规添加它,如果有符号的整数是负使用无符号减法的常规添加。这两种* _ui程序采取unsigned long类型作为最后的参数。是前pression

In other words, if the signed integer is positive, add it using the routine of unsigned addition, if the signed integer is negative add it using the routine of unsigned subtraction. Both *_ui routines take unsigned long as last arguments. Is the expression

-l

在四溢的风险?

推荐答案

如果你想避免溢出,应先投 N 来一个unsigned int,然后应用一元减吧。

If you want to avoid the overflow, you should first cast n to an unsigned int and then apply the unary minus to it.

unsigned abs(int n) {
  if (n >= 0)
    return n;
  return -((unsigned)n);
}

在原来的code否定类型转换之前发生的,所以如果的行为是未定义N'LT; -INT_MAX

In your original code the negation happens before the type conversion, so the behavior is undefined if n < -INT_MAX.

在否定一个无符号的前pression,绝不会有溢出。相反,其结果将是模 2 ^ X X 的适当的值。

When negating an unsigned expression, there will never be overflow. Instead the result will be modulo 2^x, for the appropriate value of x.

这篇关于一元减并签署对无符号的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆