4
1

typedef を用いた構造体の定義(C言語)

Last updated at Posted at 2024-03-12

型名を省略する目的 で使われるtypedef は、struct とセットで以下のように記述されることが多いです。

Employee 型の定義
typedef struct employee {
    int id;
    string name;
} Employee;

上記は 構造体 struct employeeEmployee という型名で省略できるようにした という意味になります。

struct の後の employee は構造体のタグ名と呼ばれます。

C言語の場合

typedef を用いない場合、Employee 型の変数を定義する際にstruct employee と記述する必要があり冗長です。

typedef なし
#include <stdio.h>

struct employee {
    int id;
    char* name;
};

int main(void) {
    struct employee e = {1234, "Taro"}; // 冗長...
    printf("%d\n", e.id);   // 1234
    printf("%s\n", e.name); // Taro
    return 0;
}

そこで、typedefを用いてEmployee だけで定義できるようにします。

typedef あり
#include <stdio.h>

typedef struct employee {
    int id;
    char* name;
} Employee;

int main(void) {
    Employee e = {1234, "Taro"}; // Employee のみで定義できる
    printf("%d\n", e.id);
    printf("%s\n", e.name);
    return 0;
}

もし typedefによる型名の宣言をせず、structのタグ名で定義しようとした場合は、コンパイルエラーになります。

構造体のタグ名だけでは宣言できない(コンパイルエラー)
#include <stdio.h>

struct Employee {
    int id;
    char* name;
};

int main(void) {
    Employee e = {1234, "Taro"}; // エラー
    printf("%d\n", e.id);
    printf("%s\n", e.name);
    return 0;
}

エラー文を見ると、「Employee という型名なんて知りません、struct を使って参照しなさい」という内容になっています。

prog.c:9:5: error: unknown type name 'Employee'; use 'struct' keyword to refer to the type
    9 |     Employee e = {1234, "Taro"}; // エラー
      |     ^~~~~~~~
      |     struct 

C++の場合

C言語の場合と同様に、typedefで構造体の型名を宣言できます。

typedef を用いた構造体の定義
#include <iostream>
using namespace std;

typedef struct employee {
    int id;
    string name;
} Employee;

int main() {
    Employee e = {1234, "Taro"};
    cout << e.id << endl;    // 1234
    cout << e.name << endl;  // Taro
    return 0;
}

しかしながら、C++においては typedef を使う必要がありません
実際、以下のプログラムは正常に動作します。

c++では typedef 不要
#include <iostream>
using namespace std;

struct Employee {
    int id;
    string name;
};

int main() {
    Employee e = {1234, "Taro"};
    cout << e.id << endl;    // 1234
    cout << e.name << endl;  // Taro
    return 0;
}

C++では、

struct Employee {};

typedef struct Employee {} Employee;

は等価であると考えることができます(stack overflowの記事を参照)。

参考サイト

  1. 山田 修司、プログラミングB (C言語) 構造体 https://www.cc.kyoto-su.ac.jp/~yamada/programming/struct.html(参照日:2024/03/12)
  2. stack overflow, "Difference between 'struct' and 'typedef struct' in C++?" https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c/612476 (参照日:2024/03/12)
4
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1