Is negating INT_MIN undefined behaviour?

前端 未结 3 589
别那么骄傲
别那么骄傲 2021-01-03 08:34

Let\'s say I have a variable i that comes from external sources:

int i = get_i();

Assuming i is INT_MIN

3条回答
  •  感动是毒
    2021-01-03 09:11

    Is negating INT_MIN undefined behaviour?

    Yes, when INT_MIN < -INT_MAX - which is very common (2's complement). It is integer overflow.

    int i = get_i();
    
    #if INT_MIN < -INT_MAX
    if (i == INT_MIN) {
      fprintf(stderr, "Houston, we have a problem\n");
      // Maybe return or exit here.
    }
    #endif 
    
    int j = -i;
    

    Houston, we have a problem

提交回复
热议问题