1

Possible Duplicate:
sizeof (int) == sizeof (void*)?

I was wondering whether it is guaranteed that, in both 32-bit and 64-bit systems, sizeof(int) is always equal to sizeof(void*) (i.e. 32 and 64 bits respectively).

Additionally, I need to know whether it is always guaranteed that a long int can accommodate the bits of an int and a void* together, e.g.

long int lint = (((int)integer)<<sizeof(int)) | (void*)ptr;
Community
  • 1
  • 1
Bill Kotsias
  • 3,258
  • 6
  • 33
  • 60

4 Answers4

7

I was wondering whether it is guaranteed that, in both 32-bit and 64-bit systems, sizeof(int) is always equal to sizeof(void*)

No.

I need to know whether it is always guaranteed that a long int can accommodate the bits of an int and a void* together

No. A quick proof is to consider that sizeof(long int) == sizeof(int) on many modern platforms, probably including the one you're using.

The more important question is why you think you "need to know" this; the fact that you're asking such questions makes me concerned that your code is likely to be ... wobbly.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 3
    To give an example for the first "no": Using gcc `sizeof(int)` is 4 on 64-bit platforms (whereas `sizeof(void*)` is 8 of course). – sepp2k Feb 11 '12 at 22:14
2

The size of an int is implementation dependent and though it may turn out to be equal to the size of a pointer in many systems, there is no guarantee.

If you decide you need code to depend on this, you can include something such as:

if (sizeof(int) != sizeof(void *))
{
    fprintf(stderr, "ERROR: size assumptions are invalid; this program cannot continue.\n");
    exit(-1);
}
mah
  • 39,056
  • 9
  • 76
  • 93
1

Recent C99 standard provides a <stdint.h> header defining an intptr_t integral type guaranteed to have the same size as pointers.

On my Debian/AMD64/Sid, sizeof(int) is 4 bytes, but sizeof(void*) and sizeof(intptr_t) and sizeof(long) are all 8 bytes.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

I was wondering whether it is guaranteed that, in both 32-bit and 64-bit systems, sizeof(int) is always equal to sizeof(void*) (i.e. 32 and 64 bits respectively).

No.

Additionally, I need to know whether it is always guaranteed that a long int can accommodate the bits of an int and a void* together

No.

What you are looking for is: std::intptr_t

sizeof(std::intptr_t) == sizeof(void*)

std::intptr_t is defined as an integer of a size sufficient to hold a pointer.

Technically its optional part of the standard.
But you can usually find in the header file <cstdint> See: 18.4.1 Header <cstdint> synopsis [cstdint.syn]

Martin York
  • 257,169
  • 86
  • 333
  • 562