【学习笔记】【C语言】typedef
1.概念
我们可以使用typedef关键字为各种数据类型定义一个新名字(别名)。
2.作用:给已经存在的类型起一个新的名称
3.使用场合:
1> 基本数据类型
2> 指针
3> 结构体
4> 枚举
5> 指向函数的指针
4.代码
1 #include <stdio.h> 2 3 typedef int MyInt; 4 typedef MyInt MyInt2; 5 6 // 给指针类型char *起一个新的类型名称String 7 typedef char * String; 8 9 /* 10 struct Student 11 { 12 int age; 13 }; 14 typedef struct Student MyStu; 15 */ 16 17 /* 18 typedef struct Student 19 { 20 int age; 21 } MyStu; 22 */ 23 24 25 typedef struct 26 { 27 int age; 28 } MyStu; 29 30 /* 31 enum Sex {Man, Woman}; 32 typedef enum Sex MySex; 33 */ 34 35 typedef enum { 36 Man, 37 Woman 38 } MySex; 39 40 41 typedef int (*MyPoint)(int, int); 42 43 int minus(int a, int b) 44 { 45 return a - b; 46 } 47 48 int sum(int a, int b) 49 { 50 return a + b; 51 } 52 /* 53 struct Person 54 { 55 int age; 56 }; 57 58 typedef struct Person * PersonPoint; 59 */ 60 61 typedef struct Person 62 { 63 int age; 64 } * PersonPoint; 65 66 int main() 67 { 68 // 定义结构体变量 69 struct Person p = {20}; 70 71 PersonPoint p2 = &p; 72 73 //struct Person *p2 = &p; 74 75 //MyPoint p = sum; 76 //MyPoint p2 = minus; 77 //int (*p)(int, int) = sum; 78 79 //int (*p2)(int, int) = minus; 80 81 //p(10, 11); 82 83 84 //MySex s = Man; 85 //enum Sex s = Man; 86 //enum Sex s2 = Woman; 87 88 // struct Student stu3; 89 //MyStu stu = {20}; 90 //MyStu stu2= {21}; 91 92 return 0; 93 } 94 95 void test2() 96 { 97 String name = "jack"; 98 99 printf("%s\n", name); 100 } 101 102 void test() 103 { 104 int a; 105 MyInt i = 10; 106 MyInt2 c = 20; 107 108 MyInt b1, b2; 109 110 printf("c is %d\n", c); 111 }
使用注意
1 #include <stdio.h> 2 3 //#define Integer int 4 5 //typedef int Integer; 6 7 //typedef unsigned long int MyInt; 8 9 #define String2 char * 10 11 typedef char * String; 12 13 int main() 14 { 15 /* 16 int a,b; 17 int a; 18 int b; 19 */ 20 21 //s1、s2是char *指针 22 String s1, s2; 23 /* 24 String s1; 25 String s2; 26 */ 27 s1 = "jack"; 28 s2 = "rose"; 29 30 // s3才是char *指针,s4只是char 31 String2 s3, s4; 32 /* 33 char *s3, s4; 34 char *s3; 35 char s4; 36 */ 37 //String2 s3 = "jake"; 38 39 /* 40 String s1; 41 String s2; 42 */ 43 44 45 46 47 //Integer i = 10; 48 49 return 0; 50 }