常用整型的取值范围

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

void get_limits_1(void);
void get_limits_2(void);

int main()
{
    get_limits_1();
    printf("\n===================================\n");
    get_limits_2();
    return 0;
}


void get_limits_1(void)
{
    printf("signed char min\t\t= %d\n", SCHAR_MIN);
    printf("signed char max\t\t= %d\n", SCHAR_MAX);
    printf("signed short min\t= %d\n", SHRT_MIN);
    printf("signed short max\t= %d\n", SHRT_MAX);
    printf("signed int min\t\t= %d\n", INT_MIN);
    printf("signed int max\t\t= %d\n", INT_MAX);
    printf("signed long min\t\t= %ld\n", LONG_MIN);
    printf("signed long max\t\t= %ld\n", LONG_MAX);

    printf("unsigned char max\t= %u\n", UCHAR_MAX);
    printf("unsigned short max\t= %u\n", USHRT_MAX);
    printf("unsigned int max\t= %u\n", UINT_MAX);
    printf("unsigned long max\t= %lu", ULONG_MAX);
}

void get_limits_2(void)
{
    printf("signed char min\t\t= %d\n", -(char)((unsigned char) ~0 >> 1) - 1);
    printf("signed char max\t\t= %d\n", (char)((unsigned char) ~0 >> 1));
    printf("signed short min\t= %d\n", -(short)((unsigned short) ~0 >> 1) - 1);
    printf("signed short max\t= %d\n", (short)((unsigned short) ~0 >> 1));
    printf("signed int min\t\t= %d\n", -(int)((unsigned int) ~0 >> 1) - 1);
    printf("signed int max\t\t= %d\n", (int)((unsigned int) ~0 >> 1));
    printf("signed long min\t\t= %ld\n", -(long)((unsigned long) ~0 >> 1) - 1);
    printf("signed long max\t\t= %ld\n", (long)((unsigned long) ~0 >> 1));

    printf("unsigned char max\t= %u\n", (unsigned char) ~0);
    printf("unsigned short max\t= %u\n", (unsigned short) ~0);
    printf("unsigned int max\t= %u\n", (unsigned int) ~0);
    printf("unsigned long max\t= %lu\n", (unsigned long) ~0);
}

// 结果如下:
signed char min         = -128
signed char max         = 127
signed short min        = -32768
signed short max        = -32768
signed int min          = -2147483648
singed int max          = 2147483647
signed long min         = -2147483648
signed long max         = 2147483647
unsigned char max       = 255
unsigned short max      = 65535
unsigned int max        = 4294967295
unsigned long max       = 4294967295

发表评论

电子邮件地址不会被公开。 必填项已用*标注