On hardware with fixed width registers, it is possible for an integer math operation to overflow/wrap/underflow. For example, when working with 32 bit unsigned integers, UINT_MAX + 1 will result in 0, while UINT_MAX + UINT_MAX = 4294967294 (ie, UINT_MAX -1). Similarly, -1 + INT_MIN = 2147483647. Due to the security implications of integer overflow, it would be great if GCC would provide an intrinsic for fetching relevant status flags. For signed integers on x86/x64 PCs, the flag of interest is OVERFLOW. For unsigned integers, the flag of interest is CARRY. Many [other] popular architectures, such as ARM processors, include similar flags (in the case of ARM, it is available in the Current Program Status Register (CPSR)). I envision one of two intrinsics. The first intrinsic would simply return the value of the flag (carry shown, overflow similar): uint32_t a, b; .... uint32_t r = a + b; unsigned int cy = __get_carry_flag(); A second version of the same would accept an lvaue: uint32_t a, b, r; unsigned int cy; r = a + b; __get_carry_flag(&cy); With carry/overflow in hand, a programmer would be enabled to perform safe math on data, without the need/overhead for a big integer package. For example: uint32_t r = a + b; unsigned int cy = __get_carry_flag(); if(cy) { fprintf(stderr, "Integer addition overflowed\n"); abort(); } A third system would include integer math handlers. Upon program startup, the process would register 'failed add', 'failed subtract', etc, handlers. A program could perform safe integer math as follows: uint32_t r = a + b; test_uadd_result(); An executing program which was not interested in carry/overflow handling would simply call the operation without the subsequent test: uint32_t r = a + b; // No test, who cares? Though this feature request was filed C, both C++ and Objective C would benefit from the intrinsic.
The proposed interface, with its references to global flags set by operations that otherwise have values but no side effects, is not a good match to the nature of C as a high-level language; the source code arithmetic operations should not be presumed to have any particular correspondence to machine instructions that might set flags. Instead, I proposed a more appropriate interface for operations with explicit overflow behavior in bug 48580. *** This bug has been marked as a duplicate of bug 48580 ***
Perhaps bug #59708 is a better candidate for this issue here than bug #48580, particularly in the light of bug #48580 comment #18 and #19. Can someone change the resolution of this here to duplicate that instead?
*** This bug has been marked as a duplicate of bug 59708 ***