オブジェクト指向プログラミングa 2013年度定期試験対策要点解説 4. typedefによる型の別名定義

●typedefによる型の別名定義に関する教材資料はこちら

■問題1

  下記のmain関数の前に,下図の Integer, kilometer, Country, Ship, ArrayOfInt5 の別名を定義せよ。
その際,ただ書き写すのではなく,下図の手順1〜3のように考えながら書くこと。



#include <stdio.h>
 
/* ここに,Integer, kilometer, Country, Ship, ArrayOfInt5 の型名を typedef で定義せよ。 */





 
int main() {
 
    Integer i = 10;           /* int型の変数i */
    
    kilometer fromHome = 1.2; /* 家からの距離を表す変数 */
 
    Country myCountry = Japan; /* 国別コードを格納する変数 myCountry */
 
    Ship myShip = { 100, 100, 10, 0 }; /* シューティングゲームの自機を表す変数 myShip */
 
    ArrayOfInt5 a = { 5, 8, 1, 0, 9 }; /* int型要素5個を持つ配列変数a */
 
    printf( "i is %d\n", i );
    printf( "myCountry is %d\n", myCountry );
    printf( "myShip : x is %d, y is %d, life is %d, graphic is %d\n", myShip.x, myShip.y, myShip.life, myShip.graphic );
    for( i = 0; i < 5; i++ ) printf( "a[%d] is %d\n", i, a[i] );
 
    getchar(); getchar();
    return 0;
}

【解答例】
#include <stdio.h>
 
typedef int Integer;
 
typedef double kilometer;
 
typedef enum Country {
  America, Japan, UK, USA = 0
} Country;
 
typedef struct Ship {
  int x, y, life, graphic;
} Ship;
 
typedef  int ArrayOfInt5[ 5 ];
 
int main() {
 
    Integer i = 10;           /* int型の変数i */
    
    kilometer fromHome = 1.2; /* 家からの距離を表す変数 */
 
    Country myCountry = Japan; /* 国別コードを格納する変数 myCountry */
 
    Ship myShip = { 100, 100, 10, 0 }; /* シューティングゲームの自機を表す変数 myShip */
 
    ArrayOfInt5 a = { 5, 8, 1, 0, 9 }; /* int型要素5個を持つ配列変数a */
 
    printf( "i is %d\n", i );
    printf( "myCountry is %d\n", myCountry );
    printf( "myShip : x is %d, y is %d, life is %d, graphic is %d\n", myShip.x, myShip.y, myShip.life, myShip.graphic );
    for( i = 0; i < 5; i++ ) printf( "a[%d] is %d\n", i, a[i] );
 
    getchar(); getchar();
    return 0;
}