C++ underflow and overflow

前端 未结 4 1008
不知归路
不知归路 2020-12-11 19:15

Hi I am new in here so please let me know if anything is wrong and I will try to better the next time .

I am trying to understand how underflow and overflow works i

相关标签:
4条回答
  • 2020-12-11 19:56

    The exact behavior on overflow/underflow is only specified for unsigned types. For normal signed integer types instead the C++ standard simply says than anything can happen.

    If we're talking about x86 processor (or most other modern processors) indeed the behavior is exactly what you describe and for the CPU there is no difference between a signed value or an unsigned value (there are signed and unsigned operations, but the value themselves are just bits).

    Note that compilers can assume (and most modern optimizing compilers actually DO assume) that no signed integer overflow can occur in a correct program and for example in code like:

    int do_something();
    int do_something_else();
    
    void foo() {
        int x = do_something();
        int y = x + 1;
        if (x < y) {
            do_something();
        } else {
            do_something_else();
        }
    }
    

    a compiler is free to skip the test and the else branch in the generated code completely because in a valid program a signed int x is always less than x+1 (as signed overflow cannot be considered valid behavior). If you replace int with unsigned int however the compiler must generate code for the test and for the else branch because for unsigned types it's possible that x > x+1.

    For example clang compiles the code for foo to

    foo():                                # @foo()
            push    rax
            call    do_something()
            pop     rax
            jmp     do_something()       # TAILCALL
    

    where you can see that the ode just calls do_something twice (except for the strange handling of rax) and no mention of do_something_else is actually present. More or less the same code is generated by gcc.

    0 讨论(0)
  • 2020-12-11 20:02

    Typically yes. But since this is C++, and C++ is regulated by the C++ standard, you must know that overflows are undefined behavior.

    Although what you stated probably applies on most platforms, it's in no way guaranteed, so don't rely on it.

    0 讨论(0)
  • 2020-12-11 20:12

    Signed overflows are undefined behavior in C++.

    For example:

    INT_MIN - 1

    -INT_MIN

    are expressions that invoke undefined behavior.

    SHRT_MIN - 1 and -SHRT_MIN are not undefined behavior in an environment with 16-bit short and 32-bit int because with integer promotions the operand is promoted to int first. In an environment with 16-bit short and int, these expressions are also undefined behavior.

    0 讨论(0)
  • 2020-12-11 20:16

    The new value need not be SHRT_MAX it is undefined.

    0 讨论(0)
提交回复
热议问题