类型定义

typedef

当我们声明了一个结构之后,每次在使用的时候都要 struct 结构名 变量名 ,每次都要加一个struct,比较麻烦。这是,我们的主角typedef登场了。

C 语言提供了 typedef 关键字,您可以使用它来为类型取一个新的名字。比如 typedef int zs ,以后就可以用zs来定义一个int型了。

同理,typedef 可以给结构起一个新的名字,所以我们可以这样声明一个结构。

typedef struct {
    int id;
    char name[5];
    int age;
} info;

注意,此时info不再是一个变量,而是这个结构的别名。此后就可以使用info作为一种类型了。

define与typedef的异同

#define 是 C 指令,用于为各种数据类型定义别名,与 typedef 类似,但是它们有以下几点不同:

  • typedef 仅限于为类型定义符号名称,#define 不仅可以为类型定义别名,也能为数值定义别名,比如您可以定义 1 为 ONE。
  • typedef 是由编译器执行解释的,#define 语句是由预编译器进行处理的。

联合

联合体

union和struct很相似,他的定义方法为:

union data{
    int n;
    char ch;
    double f;
};
union data a, b, c;

但是与struct不同的是,在使用union时,所有成员共用一块内存空间。这块内存空间的大小取决与所有成员中最大的那一个。

下面有一个例子,可以直观的看到这一特点:

#include<stdio.h>
#include "style.h"
//hr()是style.h中的一个函数,用来创建分割线,这里我就不写出style.h里的内容了

typedef union info{
    int a;
    char b;
    float c;
} info;

int main(){
    info test;
    test.a = 123;
    hr('*',30);
    printf("test.a = 123\n\
print: test.a -> %d\n",test.a);
    test.b = 'a';
    hr('*',30);
    printf("test.b = 'a'\n\
print: test.a -> %d\n\
print: test.b -> %c\n",test.a,test.b);
    test.c = 123.456;
    hr('*',30);
    printf("test.b = 'a'\n\
print: test.a -> %d\n\
print: test.b -> %c\n\
print: test.c -> %f\n",test.a,test.b,test.c);
    hr('*',30);

    return 0;
}

返回结果:

******************************
test.a = 123
print: test.a -> 123
******************************
test.b = 'a'
print: test.a -> 97
print: test.b -> a
******************************
test.b = 'a'
print: test.a -> 1123477881
print: test.b -> y
print: test.c -> 123.456001
******************************

因为所有成员共用一块内存空间,所以union在初始化时不能像struct一样同时初始化多个成员。也就是说,联合体只有一个成员有效。

结构作为联合体的成员

我们可以在联合体中套一个结构。

union info{
    int id;
    char name[5];
    struct scores{
        int subjectID;
        int score;
    };
};
最后修改:2023 年 04 月 28 日
如果觉得我的文章对你有用,请随意赞赏