unsigned Modifier

This page was translated by a robot.

unsignedAny integer type can be explicitly declared as an unsigned type using the modifier.

Details

Integer types are encoded as binary integers in modern systems. If a type specification such as char, short, int, longor is accompanied long longby the keyword unsigned, the integer type is explicitly declared as unsigned. This means that the type only stores positive values ​​(including zero). Caution: If the keyword is omitted, the compiler assumes it by chardefault , with the exception of the type signed. It doesn't matter whether the keyword comes before, after, or in the middle of the type.

unsigned int        a;
int unsigned        b;
char unsigned       c;
unsigned short      d;
long unsigned long  e;
unsigned            f;

If the base type is omitted from the declaration, the compiler automatically assumes the unsigned inttype .

Unsigned integer types are often used to store quantities that can explicitly only contain positive values. However, it should be noted that calculations with these variables also only deliver unsigned results. A common mistake is counting backwards in a forloop :

4
3
2
1
0
4294967295
4294967294
4294967293
...
#include <stdio.h>

int main(){
  unsigned int i;
  for(i = 4; i>=0; i--){  // Will never terminate
    printf("%u\n", i);
  }
  return 0;
}

The maximum and minimum possible values ​​of unsignedtypes are defined in the limitslibrary .

When specifying fixed values ​​in the source code, integer values ​​can be uappended with the suffix to explicitly mark them as unsigned.

Arithmetic Conversion

In the case of assignments, initializations or casts to another integer type, the compiler may carry out arithmetic conversions . Due to the encoding of negative numbers, unsigned numbers that are too large cannot be converted correctly to a signed type, which then leads to negative values:

-294967296
printf("%d\n", (signed int) 4000000000u);

A Javascript program to illustrate the effects of cutting off bits can be found at Number System Converter .