0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

構造体書き方メモ

Posted at

はじめに

Cで構造体の書き方で4つほどパターンがあるそうです。
初学では古典的な書き方をベースに学びますが、実務ではtypedefで書いたりするそうです。
今回の「古典的な書き方」をベースに、4パターンを比較できる形でまとめてみます。

構造体の書き方 4パターン比較

パターン1:古典的(structキーワード必須)

#include <stdio.h>

struct Body {
    int no;
    char name[20];
    double height;
    double weight;
};

int main(void) {
    struct Body x = { 1, "yamada", 176.3, 68.5 };
    struct Body *p = &x;

    printf("p->no     : %d\n", p->no);
    printf("p->name   : %s\n", p->name);
    printf("p->height : %.2f\n", p->height);
    printf("p->weight : %.2f\n", p->weight);
    return 0;
}

🔹 毎回 struct Body と書く必要あり。学習用・歴史的な書き方。

パターン2:タグ + typedef(実務で最も一般的)

#include <stdio.h>

typedef struct Body {
    int no;
    char name[20];
    double height;
    double weight;
} Body;

int main(void) {
    Body x = { 1, "yamada", 176.3, 68.5 };
    Body *p = &x;

    printf("p->no     : %d\n", p->no);
    printf("p->name   : %s\n", p->name);
    printf("p->height : %.2f\n", p->height);
    printf("p->weight : %.2f\n", p->weight);
    return 0;
}

🔹 Body とだけ書けるのでスッキリ。
🔹 タグ struct Body も残るので前方宣言も可能。

パターン3:無名構造体 + typedef

#include <stdio.h>

typedef struct {
    int no;
    char name[20];
    double height;
    double weight;
} Body;

int main(void) {
    Body x = { 1, "yamada", 176.3, 68.5 };
    Body *p = &x;

    printf("p->no     : %d\n", p->no);
    printf("p->name   : %s\n", p->name);
    printf("p->height : %.2f\n", p->height);
    printf("p->weight : %.2f\n", p->weight);
    return 0;
}

🔹 Body と書けてスッキリ。
🔹 ただしタグがないので「前方宣言」ができない → 大規模開発では不便。

パターン4:変数と同時定義

#include <stdio.h>

struct Body {
    int no;
    char name[20];
    double height;
    double weight;
} x = { 1, "yamada", 176.3, 68.5 };  // ここで変数を同時に定義

int main(void) {
    struct Body *p = &x;

    printf("p->no     : %d\n", p->no);
    printf("p->name   : %s\n", p->name);
    printf("p->height : %.2f\n", p->height);
    printf("p->weight : %.2f\n", p->weight);
    return 0;
}

🔹 簡単に使えるが、複数ファイルで使うときには不便。
🔹 「小さなテストコード」用という感じ。

まとめ

  • パターン1 … 古典的。歴史的理由で struct を必ず書く。
  • パターン2 … 実務で最も使われる。typedef で省略可、前方宣言も可能。
  • パターン3 … 簡潔だけど前方宣言できない。小規模コード向け。
  • パターン4 … 変数を同時に定義。テストや一時利用向け。

実務では「パターン2(タグ+typedef)」が定番だそうです。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?