0

sizeof pointer and int

Hi I am aware that size of all pointers (char*, int*, float* etc..) is same as it has to store address of the variable. On 32 bit, address can be stored in 4 bytes and hence pointer size on 32 bit system is 4. On 64 bit, address can be stored in 8 bytes and hence pointer size on 64 bit system is 8. Is it not true for integer data type? Isn't it like int size on 32 and 64 bit is same as size of pointer. In other words, size of int on 32 bit is 4 byte and 64 bit is 8 byte. Is it true?

6th Sep 2024, 9:33 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 odpowiedzi
+ 7
In general, no. The standard only specifies a minimum size for the integral data types. Which size they will have is the implmentation specific data model chosen. A model that chooses 64bit for an int may exist, but i have not come across one yet. If you need an interger large enough to hold a pointer, you need to use uintptr_t available in the cstdint header. I am sure you know that you can always query the size of primitive data types through the use of 'sizeof'. Also, the climits header gives access to numeric limits for those data types, e.g. INT_MAX. Note, all of the above is written by a C programmer. C++ may hold language specific data types that avoid the use of climits and cstdint that I am not aware of.
6th Sep 2024, 10:26 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 3
Ani Jona 🕊 so it's: use sizeof, let the compiler figure it out ... don't assume or generalize.
6th Sep 2024, 11:27 AM
Bob_Li
Bob_Li - avatar
+ 3
That is what i would suggest, yes, Bob_Li. There are also types that guarantee to be at least of a required size. There are also types of exactly the required size. For general purposes, however, i would expect it to be best to let the compiler decide what is best...
6th Sep 2024, 12:40 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar