Programming

C ++에서 열거 형을 선언 할 때 typedef를 사용하는 이유는 무엇입니까?

procodes 2020. 5. 24. 22:01
반응형

C ++에서 열거 형을 선언 할 때 typedef를 사용하는 이유는 무엇입니까?


몇 년 동안 C ++을 작성하지 않았으므로 이제 C ++로 돌아 가려고합니다. 나는 이것을 가로 질러 포기하는 것에 대해 생각했다.

typedef enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

이게 뭐야? typedef키워드 가 왜 여기에 사용됩니까? TokenType이 선언에서 이름 이 두 번 나타나는 이유는 무엇 입니까? 시맨틱은 이것과 어떻게 다른가요?

enum TokenType
{
    blah1 = 0x00000000,
    blah2=0x01000000,
    blah3=0x02000000
};

C에서 열거 형을 첫 번째 방법으로 선언하면 다음과 같이 사용할 수 있습니다.

TokenType my_type;

두 번째 스타일을 사용하면 다음과 같이 변수를 선언해야합니다.

enum TokenType my_type;

다른 사람들이 언급했듯이 C ++에서는 차이가 없습니다. 내 생각에는 이것을 작성한 사람이 C 프로그래머이거나 C 코드를 C ++로 컴파일하는 것입니다. 어느 쪽이든 코드의 동작에는 영향을 미치지 않습니다.


다음과 같은 경우 C의 C 유산입니다.

enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
};

다음과 같은 작업을 수행해야합니다.

enum TokenType foo;

그러나 이렇게하면 :

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

당신은 선언 할 수 있습니다 :

TokenType foo;

그러나 C ++에서는 이전 정의 만 사용하고 마치 C typedef에있는 것처럼 사용할 수 있습니다.


당신은 그것을 할 필요가 없습니다. C (C ++ 아님)에서는 enum Enumname사용 하여 열거 된 형식의 데이터 요소를 참조해야했습니다. 단순화하기 위해 단일 이름 데이터 형식 으로 typedef수있었습니다 .

typedef enum MyEnum { 
  //...
} MyEnum;

열거 형의 매개 변수를 취하는 함수를 다음과 같이 정의 할 수 있습니다.

void f( MyEnum x )

더 이상

void f( enum MyEnum x )

typename의 이름이 열거 형의 이름과 같을 필요는 없습니다. 구조체에서도 마찬가지입니다.

반면에 C ++에서는 열거 형, 클래스 및 구조체에 이름으로 유형에 직접 액세스 할 수 있으므로 필요하지 않습니다.

// C++
enum MyEnum {
   // ...
};
void f( MyEnum x ); // Correct C++, Error in C

C에서는 유형을 열거 형 이외의 것으로 변경할 수 있기 때문에 좋은 스타일입니다.

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

foo(enum e_TokenType token);  /* this can only be passed as an enum */

foo(TokenType token); /* TokenType can be defined to something else later
                         without changing this declaration */

In C++ you can define the enum so that it will compile as C++ or C.


Holdover from C.


Some people say C doesn't have namespaces but that is not technically correct. It has three:

  1. Tags (enum, union, and struct)
  2. Labels
  3. (everything else)

typedef enum { } XYZ; declares an anonymous enumeration and imports it into the global namespace with the name XYZ.

typedef enum ABC { } XYZ; declares an enum named ABC in the tag namespace, then imports it into the global namespace as XYZ.

Some people don't want to bother with the separate namespaces so they typedef everything. Others never typedef because they want the namespacing.


This is kind of old, but anyway, I hope you'll appreciate the link that I am about to type as I appreciated it when I came across it earlier this year.

Here it is. I should quote the explanation that is always in my mind when I have to grasp some nasty typedefs:

In variable declarations, the introduced names are instances of the corresponding types. [...] However, when the typedef keyword precedes the declaration, the introduced names are aliases of the corresponding types

As many people previously said, there is no need to use typedefs declaring enums in C++. But that's the explanation of the typedef's syntax! I hope it helps (Probably not OP, since it's been almost 10 years, but anyone that is struggling to understand these kind of things).


In some C codestyle guide the typedef version is said to be preferred for "clarity" and "simplicity". I disagree, because the typedef obfuscates the real nature of the declared object. In fact, I don't use typedefs because when declaring a C variable I want to be clear about what the object actually is. This choice helps myself to remember faster what an old piece of code actually does, and will help others when maintaining the code in the future.


The actual answer to the "why" question (which is surprisingly ignored by the existing answers top this old question) is that this enum declaration is probably located in a header file that is intended to be cross-compilable as both C and C++ code (i.e. included into both C and C++ implementation fiules). The art of writing such header files relies on the author's ability to select language features that have the proper compatible meaning in both languages.

참고URL : https://stackoverflow.com/questions/385023/why-do-you-use-typedef-when-declaring-an-enum-in-c

반응형