Hao Shi Hao Shi - 2 months ago 9
C++ Question

c++ integer type automatic 64 bit

I am using

size_t
for unsigned integer in my code. It has an advantage, if my computer support 64 bit,
size_t
will be
unsigned long long int
, otherwise, it is
unsigned int
. My code can run on both 32 bit and 64 bit platform.

Is there a similar signed integer? If the platform only support 32 bit, it is
int
, if the platform support 64 bit, it is
long long int
.

I can achieve this by setting a flag:

#ifdef USE_INT64
#define MY_INT int
#else
#define MY_INT long long int
#endif


Then use
MY_INT
. However I need to define
USE_INT64
and include this header for all my code. If there is something similar to
size_t
, it will be great.

AnT AnT
Answer

If you want to tie your types directly to address width, then the types you are looking for are called uintptr_t and intptr_t. They are inherited from C standard library through <cstdint>.

Type size_t is not guaranteed to have the same size as pointer (it is smaller in general case), meaning that it can be used as a reference point for that purpose on your platform only.

Of course, the real question here is whether there's a good underlying reason to tie your integer type to address width. If not, a better idea would be to define your types directly through uintNN_t/intNN_t typedefs and forget about size_t and such.