Is it safe to subtract unsigned integers?

The following C code displays the result correctly -1.

#include <stdio.h>

main()
{

    unsigned x = 1;
    unsigned y=x-2;

   printf("%d", y );

}
  • But in general, is it always safe to do a subtraction involving unsigned integers?
  • The reason I ask this question is because I want to make some conditions as follows:

    unsigned x = 1; // x was defined by someone else as unsigned, 
    // which I had better not to change.
    for (int i=-5; i<5; i++){
      if (x+i<0) continue
      f(x+i); // f is a function
    }
    

    Is it safe to do this?

  • How do unsigned integers and signed integers differ in representing integers? Thank!

+4
source share
7 answers

1: , . , , , . ( ).

: printf("%d", y); undefined, %d int, unsigned int. %u, .

2: x+i, i unsigned. unsigned. unsigned , .

, , . 2, f, x UINT_MAX ? f?

3: " " .

. ; . , , . , , UINT_MAX+1 ..

, unsigned char *p = (unsigned char *)&x; printf("%02X%02X%02X%02X", p[0], p[1], p[2], p[3]);, , .

+6
  • unsigned,

    unsigned x = 1;
    unsigned y=x-2;
    

    y -1 mod (UINT_MAX + 1) UINT_MAX.
    , , , - UB. , UINT_MAX+1.

    printf("%d", y ); - UB. printf("%u", y);

    C11 Β§6.2.5 9 " , , , , , ."

  • unsigned int +, int unsigned. , x+i unsigned < 0. , if (x+i<0) continue . f(x+i); , f(), , .

  • 0 (2, N) -1 "" . 2 , 1 UB . , .

+4

, , , , .

-, unsigned , , , . 20 , . unsigned , ( ..) . , , , : " , ".

, x unsigned - , , - x , .

"" , , , x. , a int 32 . a unsigned int . , x 2 ^ 31-1 ( ), x , .. :

int y = (int)x;

// Do your stuff with *y*

x = (unsigned)y;

long, , unsigned, x unsigned, :

long y = (long)x;

// Do your stuff with *y*

x = (unsigned)y;

, x (, x=(unsigned)y; ), , y . , , unsigned x , - :

long y = (long)x;

// Do your stuff with *y*

assert( y >= 0L );
x = (unsigned)y;

, , , , , , , .

+3

, . unsigned ints . , % u ints.

, % u printf:

#include <stdio.h>

main()
{

    unsigned x = 1;
    unsigned y=x-2;

   printf("%u", y );
}

4294967295

+1

, , , C int (% d). , , , . , (% u), .

+1

, .

4 , 32 . :

, , -2^31 2^31 - 1

, 0 2^32 - 1.


2 , 1. int unsigned -, , , , x + i.

+1

, -, " ", , (MAX_VALUE + 1). , "unsigned int" 16 ; 32 , .

- nitty-gritty, [ ] ( ), ( ). N , N ; -N N, , + N .

, -1 16- 65535, , 1 65535 0. -2 65534 ..

, , , (. 16- 8- ], . , C , ; .

, , , int, , , , . , , , . , , , (.. Integer ). , , .

+1

Source: https://habr.com/ru/post/1535292/


All Articles