数据和C(4)

本片摘要:

1:针对整数溢出问题的情况分析

2:对short ,long ,long long ,unsigned 等情况的分析

---------------------------------------------------------------------------------------------------------------------------------

整数溢出:

#include <stdio.h>

int main()
{
	int i = 217483647;
	unsigned int j = 4294967295;
	
	printf("%d, %d, %d\n",i,i+1,i+2);
    printf("%u, %u, %u\n",j,j+1,j+2);
   
   return 0;
}

运行结果:

217483647, 217483648, 217483649
4294967295, 0, 1

 分析:我们可以将这里的j看作是汽车的里程表,当它达到最大值时,会重新从起点开始,即为:0.

而整数i则是从-2147483648开始

对short ,long ,long long ,unsigned 等情况的分析:

 

在C/C++编程语言中,基本数据类型的修饰符如shortlonglong longunsigned用来定义变量的大小范围和符号特性。以下是对这些修饰符的详细分析:

short

  • 定义: shortshort int
  • 大小: 至少16位(2字节),通常在32位或64位系统上也是2字节
  • 范围: -32768到32767(有符号);0到65535(无符号)

long

  • 定义: longlong int
  • 大小: 至少32位(4字节),在许多64位系统上也是4字节
  • 范围: -2147483648到2147483647(有符号);0到4294967295(无符号)

long long

  • 定义: long longlong long int
  • 大小: 至少64位(8字节)
  • 范围: -9223372036854775808到9223372036854775807(有符号);0到18446744073709551615(无符号)

unsigned

  • 定义: unsigned可以与任何整型修饰符(shortintlonglong long)结合使用
  • 特性: 无符号类型(unsigned)仅表示非负数,因此可以存储更大的正整数
  • 例子: unsigned intunsigned long
#include <stdio.h>

int main() {
    short s = 32767;
    unsigned short us = 65535;
    
    long l = 2147483647;
    unsigned long ul = 4294967295;

    long long ll = 9223372036854775807;
    unsigned long long ull = 18446744073709551615U;

    printf("short: %d\n", s);
    printf("unsigned short: %u\n", us);
    printf("long: %ld\n", l);
    printf("unsigned long: %lu\n", ul);
    printf("long long: %lld\n", ll);
    printf("unsigned long long: %llu\n", ull);

    return 0;
}

 

注意事项

  1. 大小依赖: 数据类型的大小可能因编译器和硬件架构不同而有所不同。为了确保跨平台的兼容性,可以使用C标准库中的stdint.h定义,如int16_tint32_tint64_t等。
  2. 溢出: 在使用这些数据类型时,要小心整数溢出。例如,如果一个short变量的值超过了32767,它会溢出并从-32768重新开始。
 

 

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值