您的位置:首页 > 其它

C99标准学习笔记(4)——sizeof运算符

2015-06-04 16:17 381 查看
本文的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不能用于函数,不完整类型,或者位域的类型。

下面看测试程序:

#include <stdlib.h>

#include <stdio.h>

static void func()

{

return;

}

struct test;

struct test_bits {

char a;

char b:2;

char c:6;

};

int main()

{

printf("func size is %d, &func size is %d\n", sizeof(func), sizeof(&func));

printf("size of struct test is %d\n", sizeof(struct
test));

struct test_bits bits;

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

return 0;

}

编译:

test.c: In function ‘main’:

test.c:20: error: invalid application of ‘sizeof’ to incomplete type ‘struct test’

test.c:23: error: ‘sizeof’ applied to a bit-field

OK,说明对于不完整类型和位域,sizeof都不能通过编译,那么去掉对应的代码。编译通过,输出为:

func size is 1, &func size is 4

这个结果应该出乎意料——以前的我会认为sizeof用于函数,大小应该为4,比较func也可以看做函数的地址,说明sizeof不能用于函数。对于函数指针来说实际上即为指针的大小。

下面看一下sizeof在运行期间的使用:

#include <stdlib.h>

#include <stdio.h>

static void func(int n)

{

char c[n];

printf("size is %d\n", sizeof c);

return;

}

int main()

{

func(1);

func(2);

func(3);

return 0;

}

输出结果为:

size is 1

size is 2

size is 3

总结一下我的收获:
1. sizeof为运算符;
2. sizeof不能用于函数;
3. sizeof既可以在编译期间确定值,也可以再运行期间确定值。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: