Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8016024
  • 博文数量: 159
  • 博客积分: 10424
  • 博客等级: 少将
  • 技术积分: 14615
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-14 12:45
个人简介

啦啦啦~~~

文章分类
文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(10)

2011年(116)

2010年(22)

分类: C/C++

2011-10-09 23:29:49

本文的copyleft归gfree.wind@gmail.com所有,使用GPL发布,可以自由拷贝,转载。但转载请保持文档的完整性,注明原作者及原链接,严禁用于任何商业用途。
作者:gfree.wind@gmail.com
博客:linuxfocus.blog.chinaunix.net

本来认为对sizeof已经有了比较清晰的认识,没想到一读标准,发现自己还是理解错了。因为我使用sizeof都是用于静态的sizeof,也就是说sizeof的值在编译阶段就是可以确定的。当时将sizeof理解为一个宏了,用于计算类型或者变量所占用的字节数。读过C99标准,才发现sizeof既不是一个宏,更不是一个函数,而是一个operand,一个运算符啊——当然如果你愿意将operand看作一个函数,尤其是对比C++的运算符重载,我也没办法呵。最重要的是sizeof的值,既可以在编译期间确定,也可以在运行期间确定。

下面看看标准中对sizeof的一些描述,也是我们平时容易忽略的。
The sizeof operator shall not be applied to an expression that has function type or an
incomplete type, to the parenthesized name of such a type, or to an expression that
designates a bit-field member。
也就是说sizeof不能用于函数,不完整类型,或者位域的类型。

下面看测试程序:
  1. #include <stdlib.h>
  2. #include <stdio.h>

  3. static void func()
  4. {
  5.     return;
  6. }

  7. struct test;

  8. struct test_bits {
  9.     char a;
  10.     char b:2;
  11.     char c:6;
  12. };

  13. int main()
  14. {
  15.     printf("func size is %d, &func size is %d\n", sizeof(func), sizeof(&func));
  16.     printf("size of struct test is %d\n", sizeof(struct test));

  17.     struct test_bits bits;
  18.     printf("size of test_bits.b is %d\n", sizeof(bits.b));

  19.     return 0;
  20. }
编译:
  1. test.c: In function ‘main’:
  2. test.c:20: error: invalid application of ‘sizeof’ to incomplete type ‘struct test’
  3. test.c:23: error: ‘sizeof’ applied to a bit-field
OK,说明对于不完整类型和位域,sizeof都不能通过编译,那么去掉对应的代码。编译通过,输出为:
  1. func size is 1, &func size is 4
这个结果应该出乎意料——以前的我会认为sizeof用于函数,大小应该为4,比较func也可以看做函数的地址,说明sizeof不能用于函数。对于函数指针来说实际上即为指针的大小。

下面看一下sizeof在运行期间的使用:
  1. #include <stdlib.h>
  2. #include <stdio.h>

  3. static void func(int n)
  4. {
  5.     char c[n];

  6.     printf("size is %d\n", sizeof c);
  7.     return;
  8. }

  9. int main()
  10. {
  11.     func(1);
  12.     func(2);
  13.     func(3);

  14.     return 0;
  15. }
输出结果为:
  1. size is 1
  2. size is 2
  3. size is 3

总结一下我的收获:
1. sizeof为运算符;
2. sizeof不能用于函数;
3. sizeof既可以在编译期间确定值,也可以再运行期间确定值。
阅读(8102) | 评论(1) | 转发(3) |
给主人留下些什么吧!~~

tekkamanninja2011-10-11 09:13:56

总结的不错~~~~