C语言—sizeof()

作者:追风剑情 发布于:2019-7-10 20:46 分类:C

示例


  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. //最初K&R给出的关键字
  5. int int_size = sizeof(int);
  6. int short_size = sizeof(short);
  7. int long_size = sizeof(long);
  8. int unsigned_size = sizeof(unsigned);
  9. int char_size = sizeof(char);
  10. int float_size = sizeof(float);
  11. int double_size = sizeof(double);
  12.  
  13. //C90标准添加的关键字
  14. int signed_size = sizeof(signed);
  15. //void
  16.  
  17. //C99标准添加的关键字
  18. int bool_size = sizeof(_Bool);//布尔值
  19. //int complex_size = sizeof(_Complex);//复数
  20. //int imaginary_size = sizeof(_Imaginary);//虚数
  21.  
  22. //long、short、unsigned、signed用来修饰int
  23. signed short int ss_int = 0;
  24. unsigned short int us_int = 0;
  25. signed long int sl_int = 0;
  26. unsigned long int ul_int = 0;
  27. long long int ll_int = 0;
  28. long double ld_int = 0;
  29. //......
  30.  
  31. //打印每种数据类型所占字节数
  32. printf("--------sizeof------\n");
  33. printf("sizeof(int) \t %d \n", int_size);
  34. printf("sizeof(short) \t %d \n", short_size);
  35. printf("sizeof(long) \t %d \n", long_size);
  36. printf("sizeof(unsigned) \t %d \n", unsigned_size);
  37. printf("sizeof(char) \t %d \n", char_size);
  38. printf("sizeof(float) \t %d \n", float_size);
  39. printf("sizeof(double) \t %d \n", double_size);
  40. printf("sizeof(signed) \t %d \n", signed_size);
  41. printf("sizeof(_Bool) \t %d \n", bool_size);
  42.  
  43. char ch = 'A';
  44. //类型必须写在括号里
  45. printf("%u", sizeof(char));
  46. //变量可以不写在括号里
  47. printf("%u", sizeof ch);
  48. printf("%u", sizeof(ch));
  49.  
  50. getchar();
  51. }


运行测试

111111.png

注意 类型可移植性

       sizeof运算符以字节为单位返回类型或值的大小。这应该是某形式的整数,但是标准只规定了该值是无符号整数。在不同的实现中,它可以是unsigned int、unsigned long甚至是unsigned long long。因此,如果要用printf()函数显示sizeof表达式,根据不同系统,可能使用%u、%lu或%llu。这意味着要查找你当前系统的用法,如果把程序移植到不同的系统还要进行修改。鉴于此,C提供了可移植性更好的类型。首先,stddef.h头文件(在包含stdio.h头文件时已包含其中)把size_t定义成系统使用sizeof返回的类型,这被称为底层类型(underlying type)。其次,printf()使用z修饰符表示打印相应的类型。同样,C还定义了ptrdiff_t类型和t修饰符来表示系统使用的两个地址差值的底层有符号整数类型。

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号