您所在的位置:小祥子 » 编程 » IOS » 正文

【学习笔记】【C语言】typedef

时间:2015-07-04 编辑:登山赏枫 来源:Cnblogs

1.概念

我们可以使用typedef关键字为各种数据类型定义一个新名字(别名)。

2.作用:给已经存在的类型起一个新的名称

3.使用场合:
 1> 基本数据类型
 2> 指针
 3> 结构体
 4> 枚举
 5> 指向函数的指针

4.代码

 #include <stdio.h>
 
 typedef int MyInt;
 typedef MyInt MyInt2;
 
 // 给指针类型char *起一个新的类型名称String
 typedef char * String;
 
 /*
 struct Student
 {
     int age;
 };
 typedef struct Student MyStu;
 */
 
 /*
 typedef  struct Student
 {
     int age;
 } MyStu;
 */
 
 
 typedef struct
 {
     int age;
 } MyStu;
 
 /*
 enum Sex {Man, Woman};
 typedef enum Sex MySex;
 */
 
 typedef enum {
     Man,
     Woman
 } MySex;
 
 
 typedef int (*MyPoint)(int, int);
 
 int minus(int a, int b)
 {
     return a - b;
 }
 
 int sum(int a, int b)
 {
     return a + b;
 }
 /*
 struct Person
 {
     int age;
 };
 
 typedef struct Person * PersonPoint;
 */
 
 typedef struct Person
 {
     int age;
 } * PersonPoint;
 
 int main()
 {
     // 定义结构体变量
     struct Person p = {20};
     
     PersonPoint p2 = &p;
     
     //struct Person *p2 = &p;
     
     //MyPoint p = sum;
     //MyPoint p2 = minus;
     //int (*p)(int, int) = sum;
     
     //int (*p2)(int, int) = minus;
     
     //p(10, 11);
     
     
     //MySex s = Man;
     //enum Sex s = Man;
     //enum Sex s2 = Woman;
     
    // struct Student stu3;
     //MyStu stu = {20};
     //MyStu stu2= {21};
     
     return 0;
 }
 
 void test2()
 {
     String name = "jack";
     
     printf("%s\n", name);
 }
 
 void test()
 {
     int a;
     MyInt i = 10;
     MyInt2 c = 20;
     
     MyInt b1, b2;
     
     printf("c is %d\n", c);
 }

使用注意

 #include <stdio.h>
 
 //#define Integer int
 
 //typedef int Integer;
 
 //typedef unsigned long int MyInt;
 
 #define String2 char *
 
 typedef char * String;
 
 int main()
 {
     /*
     int a,b;
     int a;
     int b;
     */
     
     //s1、s2是char *指针
     String s1, s2;
     /*
      String s1;
      String s2;
      */
     s1 = "jack";
     s2 = "rose";
     
     // s3才是char *指针,s4只是char
     String2 s3, s4;
     /*
     char *s3, s4;
     char *s3;
     char s4;
     */
     //String2 s3 = "jake";
     
     /*
     String s1;
     String s2;
     */
     
     
     
     
     //Integer i = 10;
     
     return 0;
 }
 
关键词:学习 笔记