Question about C behaviour for unsigned integer underflow

落花浮王杯 提交于 2019-11-26 04:28:57

问题


I have read in many places that unsigned integer overflow is well-defined in C unlike the signed counterpart.

Is underflow the same?

For example:

unsigned int x = -1; // Does x == UINT_MAX?

Thanks.

I can\'t recall where, but i read somewhere that arithmetic on unsigned integral types is modular, so if that were the case then -1 == UINT_MAX mod (UINT_MAX+1).


回答1:


§6.2.5, paragraph 9:

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

Edit:

Sorry, wrong reference, but the result is still pinned down. The correct reference is §6.3.1.3 (signed and unsigned integer conversion):

if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

So yes, x == UINT_MAX.




回答2:


-1, when expressed as a 2's complement number, amounts to 0xFF...F for how ever many bits your number is. In an unsigned number space that value is the maximum value possible (i.e. all the bits are set). Therefore yes, x == UINT_MAX. The following code emits "1" on a C99 strict compiler:

#include <stdio.h>
#include <stdint.h>
#include <limits.h>

int main(int argc, char **argv){
  uint32_t x = -1;      
  printf("%d", x == UINT_MAX ? 1 : 0);
  return 0;
}



回答3:


You are mixing signed and unsigned numbers, which is uncool.

unsigned int x = 0u - 1u; // is OK though


来源:https://stackoverflow.com/questions/2760502/question-about-c-behaviour-for-unsigned-integer-underflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!