简单方法确定C语言的char/short/int/long类型取值范围和字节数

一、如何简单 快速 确认char/short/int/long类型的取值范围,示例如下:

/*
 * @Description:  
 * @version:  V1.0
 * @Company: Twirling in time
 * @Author: Lipingping
 * @Date: 2019-06-29 19:01:45
 * @LastEditors: Lipingping
 * @LastEditTime: 2019-06-29 19:17:12
 */
#include <stdio.h>
#include <limits.h>

int main()
{
    printf("About type: char\n");
    printf("The value of INT_MAX is %i\n", CHAR_MAX);
    printf("The value of INT_MIN is %i\n", CHAR_MIN);
    printf("An takes %d bytes\n\n", sizeof(char));

    printf("About type: signed short int\n");
    printf("The value of INT_MAX is %i\n", SHRT_MAX);
    printf("The value of INT_MIN is %i\n", SHRT_MIN);
    printf("An takes %d bytes\n\n", sizeof(short));

    printf("About type: int\n");
    printf("The value of INT_MAX is %i\n", INT_MAX);
    printf("The value of INT_MIN is %i\n", INT_MIN);
    printf("An takes %d bytes\n\n", sizeof(int));

    printf("About type: signed long int\n");
    printf("The value of INT_MAX is %li\n", LONG_MAX);
    printf("The value of INT_MIN is %li\n", LONG_MIN);
    printf("An takess %d bytes\n\n", sizeof(signed long int));

    return 0;
}

二、结论:

About type: char
The value of INT_MAX is 127
The value of INT_MIN is -128
An takes 1 bytes

About type: signed short int
The value of INT_MAX is 32767
The value of INT_MIN is -32768
An takes 2 bytes

About type: int
The value of INT_MAX is 2147483647
The value of INT_MIN is -2147483648
An takes 4 bytes

About type: signed long int
The value of INT_MAX is 9223372036854775807
The value of INT_MIN is -9223372036854775808
An takess 8 bytes

三、Reason:

INT类型的取值范围取决于它最终对应的存储区域的大小。存储区域的大小是一个目标平台相关的信息,由编译器来决定。在一般的32位机器上,一个INT类型的变量最终会(由编译器)分配到4字节的内存区域,恰好是机器的字长。至于一个特定硬件平台的INT类型的大小,需要查看对应的编译器的文档。

如果要较好的移植性,考虑使用C99规范里定义的uint8_t,uint16_t等定长类型,他们保证在各种处理器编译器上结果是一样的,而且你可以用位移操作(bitwise operation),不用担心编译器和处理器的问题。

发布了60 篇原创文章 · 获赞 61 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/Brouce__Lee/article/details/94194078