更新时间:2023-02-09 20:32:06
我对 C 很陌生,但我注意到如果你减少一个无符号类型,它将被分配最大值.
I'm pretty new to C but I noticed that if you decrement an unsigned type it will be assigned the maximum value.
我包含了 limits.h
只是为了比较结果.
I've included limits.h
just to compare the results.
#include <stdio.h>
#include <limits.h>
int main(void)
{
unsigned char c;
unsigned short s;
unsigned int i;
unsigned long l;
// char
printf("UCHAR_MAX = %u\n", UCHAR_MAX);
printf("UCHAR_MAX = %u\n", --c);
// short
printf("USHRT_MAX = %u\n", USHRT_MAX);
printf("USHRT_MAX = %u\n", --s);
// int
printf("UINT_MAX = %u\n", UINT_MAX);
printf("UINT_MAX = %u\n", --i);
// long
printf("ULONG_MAX = %lu\n", ULONG_MAX);
printf("ULONG_MAX = %lu\n", --l);
}
结果:
UCHAR_MAX = 255
UCHAR_MAX = 255
USHRT_MAX = 65535
USHRT_MAX = 65535
UINT_MAX = 4294967295
UINT_MAX = 4294967295
ULONG_MAX = 18446744073709551615
ULONG_MAX = 140731079060271
正如你所看到的,除了长时间之外,它对所有人都有效,至于为什么......好吧,也许有人比我更有经验可以解释.
As you can see it works for all except long, as to why.. well maybe someone more experienced than me can explain.