반응형
[C] 열거형 타입 enum 이란?을 먼저 읽고 오시는 것을 권장 드립니다.
enum 타입은 typedef 키워드와 주로 함께 사용된다.
typedef는 타입의 별칭을 생성하고 실제 타입 이름 대신 별칭을 사용할 수 있게 한다.
#include <stdio.h>
typedef enum Season
{
SPRING,
SUMMER,
FALL,
WINTER.
}SEASON;
int main(void)
{
SEASON birthday = FALL;
printf("%d\n", birthday);
}
typedef로 명시적 타입을 사용하면서 버그와 에러를 줄일 수 있다.
#include <iostream>
#include <string>
using namespace std;
typedef enum Season
{
SPRING,
SUMMER,
FALL,
WINTER,
} SEASON;
int main(void)
{
int season;
season = WINTER;
cout << season << endl;
season = 5;
cout << season << endl;
}
season 변수 목적은 SEASON 타입에 있는 값을 사용하기 위함이다.
0~3 까지의 값만 허용해야 하는데 범위 밖의 값도 허용하게 되었다.
SEASON season; 을 사용하면서 Compile Error를 내어서
시행착오를 줄일 수 있다.
명시적 타입을 사용하면서 보다 높은 안전성을 가질 수 있는데,
→ string GetSeason(SEASON season) {...}
함수 활용할 때도 가독성을 높여주기도 한다.
#include <iostream>
#include <string>
using namespace std;
typedef enum Season
{
SPRING,
SUMMER,
FALL,
WINTER,
}SEASON;
string GetSeason(SEASON season)
{
string ret = "";
switch (season)
{
case SPRING:
ret = "봄"; break;
case SUMMER:
ret = "여름"; break;
case FALL:
ret = "가을"; break;
case WINTER:
ret = "겨울"; break;
default:
break;
}
return ret;
}
int main(void)
{
Season season = WINTER;
cout << GetSeason(season) << endl;
}
반응형
'프로그래밍 언어 > C 언어' 카테고리의 다른 글
[C/C++] memset 사용시 주의사항 (0) | 2021.09.11 |
---|---|
[C / C++] memset 함수 사용 (0) | 2021.09.11 |
[C] 로그(log) 함수 (0) | 2021.09.01 |
[C] 함수 포인터와 void 포인터 (0) | 2021.03.20 |
[C] 포인터의 포인터(이중 포인터) (0) | 2021.03.20 |
댓글