您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

【學習筆記】【C 語言】typedef 的用法整理

編輯:iOS 相關資訊

1. 概念

我們可以用 typedef 關鍵字為各種資料型別定義一個新名稱(別名)。

2. 作用

為已經存在的型別取一個新的名稱。

3. 常見使用場合

1> 基本資料型別
2> 指標
3> 結構體
4> 列舉
5> 指向函式的指標

4. 程式碼示範

#include <stdio.h>

typedef int MyInt;
typedef MyInt MyInt2;

// 為指標型別 char * 取一個新的型別名稱 String
typedef char * String;

/* 結構體的三種寫法 */
typedef struct Student { int age; } MyStu;

/* 列舉 */
typedef enum { Man, Woman } MySex;

/* 函式指標 */
typedef int (*MyPoint)(int, int);

/* 結構體指標 */
typedef struct Person {
    int age;
} *PersonPoint;

int main()
{
    // 定義結構體變數
    struct Person p = {20};
    PersonPoint p2 = &p;

    MyInt i = 10;
    MyInt2 c = 20;
    MyInt b1, b2;

    MySex s = Man;

    printf("c is %d\n", c);
    return 0;
}

void test()
{
    int a;
    MyInt i = 10;
    MyInt2 c = 20;
    MyInt b1, b2;
    printf("c is %d\n", c);
}

void test2()
{
    String name = "jack";
    printf("%s\n", name);
}

5. typedef 與 #define 的差別

//#define Integer int
//typedef int Integer;
//typedef unsigned long int MyInt;

#define String2 char *
typedef char * String;

int main()
{
    // s1、s2 都是 char * 指標
    String s1, s2;

    s1 = "jack";
    s2 = "rose";

    // 只有 s3 是 char * 指標,s4 只是 char
    String2 s3, s4;

    return 0;
}

重點整理

這段對照最能說明兩者的差異:用 typedef char * String; 之後,String s1, s2; 會讓兩個變數都成為指標;而用 #define String2 char * 時,String2 s3, s4; 展開後等同 char *s3, s4;,s4 只是一個普通的 char。

原因在於 typedef 由編譯器處理,是真正的型別宣告,會遵循 C 語言的宣告語意;#define 只是預處理階段的文字替換。因此,需要型別安全性的場合應優先採用 typedef。另外,typedef 常用來簡化結構體與列舉的宣告,省去每次都要寫 struct 前綴的麻煩,這也是 iOS/Objective-C 程式碼中經常看到的寫法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved