Programming

C ++에서 int와 long의 차이점은 무엇입니까?

procodes 2020. 7. 28. 22:14
반응형

C ++에서 int와 long의 차이점은 무엇입니까?


내가 틀렸다면 교정 해

int는 4 바이트이며, 값 범위는 -2,147,483,648에서 2,147,483,647 (2 ^ 31)
이며, 길이는 4 바이트이며, 값 범위는 -2,147,483,648에서 2,147,483,647 (2 ^ 31)입니다.

C ++의 차이점은 무엇입니까? 그것들을 서로 바꿔서 사용할 수 있습니까?


구현에 따라 다릅니다.

예를 들어, Windows에서 그것들은 동일하지만, 예를 들어 Alpha 시스템에서 long은 64 비트 인 반면 int는 32 비트입니다. 기사 는 가변 플랫폼에서 Intel C ++ 컴파일러의 규칙을 다룹니다. 요약:

  OS           arch           size
Windows       IA-32        4 bytes
Windows       Intel 64     4 bytes
Windows       IA-64        4 bytes
Linux         IA-32        4 bytes
Linux         Intel 64     8 bytes
Linux         IA-64        8 bytes
Mac OS X      IA-32        4 bytes
Mac OS X      Intel 64     8 bytes  

당신이 가진 유일한 보증은 다음과 같습니다.

sizeof(char) == 1
sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

// FROM @KTC. The C++ standard also has:
sizeof(signed char)   == 1
sizeof(unsigned char) == 1

// NOTE: These size are not specified explicitly in the standard.
//       They are implied by the minimum/maximum values that MUST be supported
//       for the type. These limits are defined in limits.h
sizeof(short)     * CHAR_BIT >= 16
sizeof(int)       * CHAR_BIT >= 16
sizeof(long)      * CHAR_BIT >= 32
sizeof(long long) * CHAR_BIT >= 64
CHAR_BIT         >= 8   // Number of bits in a byte

다음을 참조하십시오 : 최소 32 비트 long보장됩니까?


x64를 컴파일 할 때 int와 long의 차이는 사용하는 컴파일러에 따라 0에서 4 바이트 사이입니다.

GCC는 LP64 모델을 사용합니다. 즉, int는 32 비트이지만 long은 64 비트 모드에서 64 비트입니다.

예를 들어 MSVC는 LLP64 모델을 사용하는데, 이는 64 비트 모드에서도 int와 long이 모두 32 비트임을 의미합니다.


C ++ 사양 자체 (이것에 대한 이전 버전하지만 충분한)이 개방을 떠난다.

' signed char', ' short int', ' int'및 ' long int'의 4 가지 부호있는 정수 유형이 있습니다 . 이 목록에서 각 유형은 목록에서 이전 유형보다 최소한 많은 스토리지를 제공합니다. 일반 int는 실행 환경의 아키텍처에서 제안한 자연스러운 크기를 가지고 있습니다.

[각주 : 즉, header에 정의 된대로 INT_MIN 및 INT_MAX 범위의 값을 포함 할만큼 충분히 큽니다 <climits>. --- 어리석은 말]


Kevin Haines가 지적했듯이 int는 실행 환경에서 제안한 자연스러운 크기를 가지며 INT_MIN 및 INT_MAX에 맞아야합니다.

C89 표준에 따르면 UINT_MAX2 ^ 16-1, USHRT_MAX2 ^ 16-1 및 ULONG_MAX2 ^ 32-1 이상이어야합니다 . 따라서 비트 수는 short와 int의 경우 16 이상, long의 경우 32입니다. char의 경우 적어도 8 비트 ( CHAR_BIT) 가 있어야한다고 명시되어 있습니다 . C ++는 limits.h 파일에 대한 규칙을 상속하므로 C ++에서는 해당 값에 대한 동일한 기본 요구 사항이 있습니다. 당신은 그러나해야 하지 그 INT 적어도 2 바이트임을에서 파생. 이론적으로, char, int 및 long은 모두 1 바이트 일 수 있으며,이 경우 CHAR_BIT32 자 이상이어야합니다. "byte"는 항상 char의 크기라는 것을 기억하십시오. 따라서 char이 더 크면 바이트는 8 비트가 아닙니다. 더.


컴파일러에 따라 다릅니다. long은 적어도 int만큼 클 것이라고 보장되지만 더 이상 길다는 보장은 없습니다.


대부분의 경우 바이트 수와 값 범위는 C ++이 아닌 CPU 아키텍처에 의해 결정됩니다. 그러나 C ++은 최소 요구 사항을 설정하며 litb는 올바르게 설명했으며 Martin York은 몇 가지 실수 만했습니다.

int와 long을 서로 바꿔서 사용할 수없는 이유는 길이가 항상 같지 않기 때문입니다. C는 바이트가 8 비트이고 int가 2 바이트이며 하드웨어 명령어에 의해 직접 처리 될 수있는 PDP-11에서 발명되었습니다. C 프로그래머는 종종 4 바이트 산술이 필요했기 때문에 오랫동안 발명되었고 라이브러리 기능에 의해 처리되는 4 바이트였습니다. 다른 기계는 사양이 다릅니다. C 표준은 몇 가지 최소 요구 사항을 부과했습니다.


Relying on the compiler vendor's implementation of primitive type sizes WILL come back to haunt you if you ever compile your code on another machine architecture, OS, or another vendor's compiler .

Most compiler vendors provide a header file that defines primitive types with explict type sizes. These primitive types should be used when ever code may be potentially ported to another compiler (read this as ALWAYS in EVERY instance). For example, most UNIX compilers have int8_t uint8_t int16_t int32_t uint32_t. Microsoft has INT8 UINT8 INT16 UINT16 INT32 UINT32. I prefer Borland/CodeGear's int8 uint8 int16 uint16 int32 uint32. These names also give a little reminder of the size/range of the intended value.

For years I have used Borland's explicit primitive type names and #include the following C/C++ header file (primitive.h) which is intended to define the explicit primitive types with these names for any C/C++ compiler (this header file might not actually cover every compiler but it covers several compilers I have used on Windows, UNIX and Linux, it also doesn't (yet) define 64bit types).

#ifndef primitiveH
#define primitiveH
// Header file primitive.h
// Primitive types
// For C and/or C++
// This header file is intended to define a set of primitive types
// that will always be the same number bytes on any operating operating systems
// and/or for several popular C/C++ compiler vendors.
// Currently the type definitions cover:
// Windows (16 or 32 bit)
// Linux
// UNIX (HP/US, Solaris)
// And the following compiler vendors
// Microsoft, Borland/Imprise/CodeGear, SunStudio,  HP/UX
// (maybe GNU C/C++)
// This does not currently include 64bit primitives.
#define float64 double
#define float32 float
// Some old C++ compilers didn't have bool type
// If your compiler does not have bool then add   emulate_bool
// to your command line -D option or defined macros.
#ifdef emulate_bool
#   ifdef TVISION
#     define bool int
#     define true 1
#     define false 0
#   else
#     ifdef __BCPLUSPLUS__
      //BC++ bool type not available until 5.0
#        define BI_NO_BOOL
#        include <classlib/defs.h>
#     else
#        define bool int
#        define true 1
#        define false 0
#     endif
#  endif
#endif
#ifdef __BCPLUSPLUS__
#  include <systypes.h>
#else
#  ifdef unix
#     ifdef hpux
#        include <sys/_inttypes.h>
#     endif
#     ifdef sun
#        include <sys/int_types.h>
#     endif
#     ifdef linux
#        include <idna.h>
#     endif
#     define int8 int8_t
#     define uint8 uint8_t
#     define int16 int16_t
#     define int32 int32_t
#     define uint16 uint16_t
#     define uint32 uint32_t
#  else
#     ifdef  _MSC_VER
#        include <BaseTSD.h>
#        define int8 INT8
#        define uint8 UINT8
#        define int16 INT16
#        define int32 INT32
#        define uint16 UINT16
#        define uint32 UINT32
#     else
#        ifndef OWL6
//          OWL version 6 already defines these types
#           define int8 char
#           define uint8 unsigned char
#           ifdef __WIN32_
#              define int16 short int
#              define int32 long
#              define uint16 unsigned short int
#              define uint32 unsigned long
#           else
#              define int16 int
#              define int32 long
#              define uint16 unsigned int
#              define uint32 unsigned long
#           endif
#        endif
#      endif
#  endif
#endif
typedef int8   sint8;
typedef int16  sint16;
typedef int32  sint32;
typedef uint8  nat8;
typedef uint16 nat16;
typedef uint32 nat32;
typedef const char * cASCIIz;    // constant null terminated char array
typedef char *       ASCIIz;     // null terminated char array
#endif
//primitive.h

The C++ Standard says it like this :

3.9.1, §2 :

There are five signed integer types : "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment (44); the other signed integer types are provided to meet special needs.

(44) that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header <climits>.

The conclusion : it depends on which architecture you're working on. Any other assumption is false.

참고URL : https://stackoverflow.com/questions/271076/what-is-the-difference-between-an-int-and-a-long-in-c

반응형