《C关键字分析》之sizeof,enum、union和struct

时间:2020-11-23 19:55:02

一、关于sizeof

1.它是C的关键字、是一个运算符,不是函数;

2.一般用法为sizeof 变量或sizeof(数据类型);后边这种写法会让人误认为是函数,但这种写法是为了防止和C中类型修饰符(static、const、extern等)冲突。

二、demo

1.源码

test.c

#include <stdio.h>

int main()
{
int i;
printf("sizeof i is %d\n",sizeof i);
/*
以下语句不屏蔽会提示:test.c:12: 错误: expected expression before ‘int’
因为,基本数据类型int前的关键字会被认为成是类型修饰符(类似static、const、extern等,而sizeof关键字不是类型修饰符)
正确写法:printf("sizeof(int) is %d\n",sizeof(int));
*/
//printf("sizeof int is %d\n",sizeof int);

enum Color{
GREEN = 1,
RED,
BLUE,
GREEN_RED = 10,
GREEN_BLUE
}ColorVal;
printf("sizeof ColorVal is %d\n",sizeof ColorVal);
/*
以下语句不屏蔽会提示:test.c:26: 错误: expected expression before ‘enum’,原因同上。
正确写法:printf("sizeof(enum Color) is %d\n",sizeof(enum Color));
*/
//printf("sizeof enum Color is %d\n",sizeof enum Color);

union check{
int i;
char ch;
} c;
printf("sizeof c is %d\n",sizeof c);
/*
以下语句不屏蔽会提示:test.c:37: 错误: expected expression before ‘enum’,原因同上。
正确写法:printf("sizeof(union check) is %d\n",sizeof(union check));
*/
//printf("sizeof union check is %d\n",sizeof union check);

struct list{
int i;
char ch;
} a;
printf("sizeof a is %d\n",sizeof a);
/*
以下语句不屏蔽会提示:test.c:48: 错误: expected expression before ‘enum’,原因同上。
正确写法:printf("sizeof(struct list) is %d\n",sizeof(struct list));
*/
//printf("sizeof struct list is %d\n",sizeof struct list);
return 0;
}
2.编译

gcc test.c -o test

3.运行

./test

sizeof i is 4
sizeof ColorVal is 4
sizeof c is 4
sizeof a is 8