C语言typedef

typedef是C语言的关键字,其作用是为数据类型定义别名。

typedef int Integer;
typedef unsigned int UInterger;
typedef float Float;

int main() {
    
    //用别名定义变量
    Integer i = 2;
    UInterger ui = 17;
    Float f = 13.14f;
  
    return 0;
}

1    typedef与指针
typedef不仅能为基本数据结构类型定义别名,还能为指针定义别名。除了基本类型指针,结构体指针以及指向函数的指针也能被定义别名。

 

typedef char *String;
// 定义一个结构体
struct Student {
    int age;
    float height;
};

// 起别名
typedef struct Student *pStudent;

// 定义一个sum函数
int sum(int a, int b) 
{
    return c = a + b;

}
//定义一个指向函数的指针的别名
typedef int (*pSum)(int, int);

int main(int argc, const char * argv[]) {
    // 相当于char *str = "zhangsan";
    String str = "zhangsan";
    
    struct Student stu = {12,123.4f};
    pStudent pStu = &stu;  //结构体指针

    pSum p = sum; //指向函数的指针
    int a = (*p)(1,2);  
   
    
    return 0;
}

2    typedef与结构体,枚举

 

enum Season {spring, summer, autumn, winter};
// 给枚举类型起别名
typedef enum Season Season;
/*简化写法
typedef enum Season {spring, summer, autumn, winter} Season;
typedef enum {spring, summer, autumn, winter} Season;
*/

// 定义一个结构体
struct Student {
    int age;
    float height;
};

// 起别名
typedef struct Student Student;

/*简化写法
typedef struct Student {
    int age;
    float height;
} Student;
typedef struct {
    int age;
    float height;
} Student;

*/

int main(int argc, const char * argv[]) {
    
    Season s = summer;
    
    Student stu;
    stu.age = 12;
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值