C언어/참고서: C언어 콘서트

[C언어 54차시] 공용체, union, 열거형, enum, typedef

Olivia-BlackCherry 2023. 4. 16. 19:19

목차

    1. 공용체 union

    같은 메모리 영역을 여러 개의 변수들이 공유하는 기능이다. 

    메모리를 절약한다. 

     

     

    1-1. 공용체 태그, 공용체 멤버 변수

    union example {
    	char c;
    	int i;
    };

    keyword: union

    union tag : example

    { };

    union member: c, i

    공용체 멤버 변수 c, i는 같은 메모리를 공유한다. 

    어떤 순간에는 이 둘 중 하나만 존재할 수 있다.

     

     

    1-2. 공용체 변수 선언

    union example a;

    변수를 선언해야 쓸 수 있다. 

    union a의 크기는, 멤버 중 메모리를 가장 많이 요구하는 멤버의 크기와 같다. 

    예컨데 example의 멤버 c, i 중 i가  int형으로 4바이트가 되므로, a의 크기도 4바이트이다.

     

     

    1-3. 선택된 멤버에 따라 저장된 값이 다름

    union 멤버에 접근할 때는 멤버 연산자인 .연산자를 이용한다. 

    선택된 멤버에 따라 저장된 값이 다르게 해석되므로, 

    프로그래머가 올바르게 값을 저장한 후, 사용해야 한다. 

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    union example {
    	char c;
    	int i;
    };
    
    int main(void)
    {
    	union example a;
    	a.c = 'A';
    	printf("%c, %d\n", a.c, a.i);
    
    	a.i = 100;
    	printf("%c, %d\n", a.c, a.i);
    }

    >>A, -858993599
    d, 100

     

     

    2. 열거형 enum

    변수가 가질 수 있는 값들을 미리 열거해놓은 자료형이다. 

    enumerate는 열거하다라는 뜻의 줄임말인 enum을 키워드로 쓴다. 

    예컨데, 요일을 저장하는 변수는 {일요일, 월요일, 화요일,~,토요일} 중 하나를 값으로

    월을 저장하는 변수는 {12월,1월,~,11월} 중 하나를 값으로 가질 것이다. 

    값이 될 수 있는 값들을 열거하여 이것을 열거형으로 선언해보자. 

     

     

    2-1. 열거형 태그, 값

    enum days {
    	sun, sat, fri, thu, wed, tues, mon
    };

    keyword: enum

    tag: days

    {};

    values:sun, mon,.., sat

    여기서 기억할 점은 값들을 나열할 때, 문자형이라도 '', ""을 쓰지 않는다는 점이다.

     

     

    2-2 열거형 값

    열거형 days는 위치에 따라 컴파일러에 의해 숫자 값이 설정된다. 

    다른 정의가 없다면 0부터 1씩 커지는 값을 배정받는다. 

    sun, sat, fri, thu, wed, tues, mon

    sun=0, sat=1, fri=2, thu=3, wed=4, tues=5, mon=6

    값을 갖는다.

     

    사용자가 변경할 수도 있다. 

    만약 2부터 시작하고 싶다면 

    sun=2, sat, fri, thu, wed, tues, mon

    sun=2, sat=3, fri=4, thu=5, wed=6, tues=7, mon=8

    값을 갖는다.

     

    sun=20, sat=40, fri=50, thu=60, wed=70, tues=80, mon=90

    sun=20, sat=40, fri=50, thu=60, wed=70, tues=80, mon=90

    값을 갖는다. 

     

     

    2-3 열거형 선언

    	enum days today;

     

     

    2-4 열거형 변수에 값 대입

    열거형 변수는 열거형 태그에 정의된 값들만을 가질 수 있다. 

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    enum days {
    	sun, sat, fri, thu, wed, tues, mon
    };
    
    int main(void)
    {
    	enum days today;
    	today = sun;
    	printf("%d\n", today);
    }

    >>0

     

     

    2-5 연습문제

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    enum days {
    	sun, sat, fri, thu, wed, tues, mon
    };
    
    int main(void)
    {
    	enum days today;
    	today = fri;
    	char* days_name[] = { "sun", "sat", "fri", "thu", "wed", "tues", "mon" };
    	
    	printf("%d\n", today);
    	printf("%s\n", days_name[today]);
    }

    >>2

    fri

     

     

    3. typedef

    type

    define

    새로운 type을 define 정의한다. 

    기본 자료형을 확장시키는 역할을 한다. 

    별명을 붙여주는 것 같기도 하다. 

    typedef를 사용하면 복잡한 데이터 형식도 새로운 자료형으로 만들 수 있다. 

     

    typedef <진짜> <별명>
    typedef int INT 

    진짜: 기존 자료형

    별명: 새로운 자료형

    진짜를 별명으로 정의한다. 

    	typedef int INT;
    	INT a;

     

    특히 struct 구조체에서 유용하게 쓰인다.

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct point {
    	char a;
    	int b;
    	double c;
    };
    int main(void) {
    	struct point p = { 'A', 2, 4.5 };
    	printf("%c %d %lf\n", p.a, p.b, p.c);
    
    	typedef struct point POINT;
    	POINT q = { 'a', 2, 4.5 };
    	printf("%c %d %lf", q.a, q.b, q.c);
    }

    >>A 2 4.500000
    a 2 4.500000

     

     

    4. 연습문제

    - 두 점 사이의 거리 구하기

    - typedef 사용하여 .구조체 자료형 재정의하기

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    double translate(int, int, int, int);
    struct point {
    	int x;
    	int y;
    };
    
    int main(void) {
    
    	typedef struct point POINT;
    	POINT p[10] = {
    		{7,3},
    		{10, 10}
    	};
    	double result;
    	result = translate(p[0].x, p[1].x, p[0].y, p[1].y);
    	printf("%lf\n",result);
    	return 0;
    }
    
    double translate(int x1, int x2, int y1, int y2)
    {
    	int diff = pow((x1 - x2), 2) + pow((y1 - y2), 2);
    	double result;
    	result = sqrt(diff);
    	return result;
    }

     

    - 두 점 사이의 거리 구하기

    - 구조체의 선언과 typedef 같이 사용하기

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    double translate(int, int, int, int);
    typedef struct point {
    	int x;
    	int y;
    }POINT;
    
    int main(void) {
    
    	POINT p[10] = {
    		{7,3},
    		{10, 10}
    	};
    	double result;
    	result = translate(p[0].x, p[1].x, p[0].y, p[1].y);
    	printf("%lf\n",result);
    	return 0;
    }
    
    double translate(int x1, int x2, int y1, int y2)
    {
    	int diff = pow((x1 - x2), 2) + pow((y1 - y2), 2);
    	double result;
    	result = sqrt(diff);
    	return result;
    }

     

    - 두 점의 평행이동에 관한 프로그램 작성하기

    - 구조체 선언과 typedef 함께 사용하기

    -  함수의 인수로 구조체를, return 값으로 구조체를 사용하기

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    typedef struct point {
    	int x;
    	int y;
    }POINT;
    POINT translate(POINT p, POINT q);
    
    int main(void) {
    
    	POINT p = { 7,3 };
    	POINT q = { 10, 10 };
    	POINT result;
    	result = translate(p, q);
    	printf("%d, %d\n",result.x, result.y);
    	return 0;
    }
    
    POINT translate(POINT p, POINT q)
    {
    	POINT new_p;
    	new_p.x = p.x + q.x;
    	new_p.y = p.y + q.y;
    	return new_p;
    }