IT TIP

항상 sizeof (enum) == sizeof (int)입니까?

itqueen 2020. 12. 12. 12:54
반응형

항상 sizeof (enum) == sizeof (int)입니까?


항상 sizeof (enum) == sizeof (int)입니까?

  • 아니면 컴파일러에 의존합니까?
  • 컴파일러가 단어 길이 (메모리 정렬)에 최적화되어 있으므로, 즉 y int가 특정 컴파일러의 단어 크기라고 말하는 것은 잘못된 것입니까? 열거 형을 사용하면 단어로 정렬되므로 처리 패널티가 없음을 의미합니까?
  • 모든 반환 코드를 열거 형에 넣는 것이 좋지 않습니까? 반환 유형을 확인하는 동안 이름 만 가져 오는 값에 대해 분명히 걱정하지 않기 때문입니다. 이 경우 메모리를 절약 할 수 있으므로 #DEFINE이 더 좋습니다.

일반적인 관행은 무엇입니까? 이러한 반환 유형을 네트워크를 통해 전송해야하고 다른 쪽 끝에서 일부 처리를 수행해야하는 경우 enums / # defines / const ints를 선호합니다.

편집-컴파일러가 매크로를 심볼릭으로 연결하지 않기 때문에 net에서 확인하면 사람들은 어떻게 디버깅하고 정수 값을 헤더 파일과 비교합니까?

답변에서 — 설명이 필요하므로 아래에이 줄을 추가합니다.

"따라서 구현에 따라 정의되고 sizeof (enum) sizeof (char), 즉 1과 같을 수 있습니다 ."

  • 컴파일러가 열거 형의 값 범위를 확인한 다음 메모리를 할당한다는 의미가 아닙니다. 나는 그렇게 생각하지 않는다. 물론 나는 모른다. 누군가 "아마"가 무엇인지 설명해 주시겠습니까?

컴파일러에 따라 다르며 열거 형마다 다를 수 있습니다. 다음은 의미론입니다.

enum X { A, B };

// A has type int
assert(sizeof(A) == sizeof(int));

// some integer type. Maybe even int. This is
// implementation defined. 
assert(sizeof(enum X) == sizeof(some_integer_type));

C99의 "일부 정수 유형"에는 확장 정수 유형도 포함될 수 있습니다 (그러나 구현시이를 제공하는 경우 문서화해야 함). 열거 타입의 모든 열거 (의 값을 저장할 수있는 유형 AB이 경우에).

열거를 사용하는 데 어떤 불이익도 없다고 생각합니다. 열거자는 정수 상수식이기도합니다 (예를 들어 정적 또는 파일 범위 변수를 초기화하는 데 사용할 수 있음). 가능하면 매크로보다 열거자를 선호합니다.

열거 자에는 런타임 메모리가 필요하지 않습니다. 열거 형 변수를 생성 할 때만 런타임 메모리를 사용할 수 있습니다. 열거자를 컴파일 시간 상수라고 생각하면됩니다.

열거 자 값 (대략적인 값 범위를 미리 알고 있어야 함)을 저장할 수있는 형식을 사용하고, 여기에 캐스팅하고, 네트워크를 통해 보낼 수 있습니다. 가급적이면 유형은 고정 너비 유형이어야합니다 (예 int32_t:). 따라서 다른 시스템이 관련 될 때 충돌이 발생하지 않습니다. 또는 번호를 인쇄하고 다른면에서 스캔하여 이러한 문제 중 일부를 제거합니다.


편집에 대한 응답

글쎄, 컴파일러는 어떤 크기도 사용할 필요가 없습니다. 쉽게 알 수있는 것은 값의 부호가 중요하다는 것입니다. 부호없는 유형은 일부 계산에서 상당한 성능 향상을 가져올 수 있습니다. 다음은 4.4.0내 상자 에서 GCC의 동작입니다.

int main(void) {
  enum X { A = 0 };
  enum X a; // X compatible with "unsigned int"
  unsigned int *p = &a;
}

-1그러나을 할당하면 GCC 는 다음과 호환되는 int유형 으로 사용하도록 선택합니다.X

int main(void) {
  enum X { A = -1 };
  enum X a; // X compatible with "int"
  int *p = &a;
}

--short-enumsGCC 옵션 을 사용하면 모든 값에 맞는 가장 작은 유형을 사용합니다.

int main() {
  enum X { A = 0 };
  enum X a; // X compatible with "unsigned char"
  unsigned char *p = &a;
}

C99, 6.7.2.2p4 말한다

열거 된 각 유형은 char, 부호있는 정수 유형 또는 부호없는 정수 유형과 호환 가능해야합니다. 유형의 선택은 구현에 따라 정의되지만 108) 열거 형의 모든 구성원 값을 나타낼 수 있어야합니다. [...]

각주 108 추가

구현은 모든 열거 상수를 볼 때까지 정수 유형 선택을 지연시킬 수 있습니다.

따라서 구현에 따라 정의되며 sizeof (enum)은 sizeof (char), 즉 1과 같을 수 있습니다.

작은 정수 범위의 크기를 선택할 때 항상 패널티가 있습니다. 메모리를 작게 만들면 처리 패널티가있을 수 있습니다. 더 크게 만들면 공간 패널티가 있습니다. 그것은 시공간 거래입니다.

Error codes are typically #defines, because they need to be extensible: different libraries may add new error codes. You cannot do that with enums.


Is the sizeof(enum) == sizeof(int), always

The ANSI C standard says:

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined. (6.7.2.2 Enumerationspecifiers)

So I would take that to mean no.

If this is the case wont #DEFINE be better as it would save memory.

In what way would using defines save memory over using an enum? An enum is just a type that allows you to provide more information to the compiler. In the actual resulting executable, it's just turned in to an integer, just as the preprocessor converts a macro created with #define in to its value.

What is the usual practise. I if i have to transport these return types over a network and some processing has to be done at the other end

If you plan to transport values over a network and process them on the other end, you should define a protocol. Decide on the size in bits of each type, the endianess (in which order the bytes are) and make sure you adhere to that in both the client and the server code. Also don't just assume that because it happens to work, you've got it right. It just might be that the endianess, for example, on your chosen client and server platforms matches, but that might not always be the case.


No.

Example: The CodeSourcery compiler

When you define an enum like this:

enum MyEnum1 {
A=1,
B=2,
C=3
};
// will have the sizeof 1 (fits in a char)

enum MyEnum1 {
A=1,
B=2,
C=3,
D=400
};
// will have the sizeof 2 (doesn't fit in a char)

Details from their mailing list


On some compiler the size of an enum is depending on how many entry's are in the Enum. (less than 255 Entrys => Byte, More than 255 Entrys int) But this is depending on the Compiler and the Compiler Settings.

참고URL : https://stackoverflow.com/questions/1113855/is-the-sizeofenum-sizeofint-always

반응형