简单方法确定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),不用担心编译器和处理器的问题。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值