Code:
#include <iostream>
#include <type_traits>
int main() {
std::cout << "sizeof(size_t): " << sizeof(size_t) << std::endl;
std::cout << "sizeof(uint64_t): " << sizeof(uint64_t) << std::endl;
if constexpr (std::is_same_v<size_t, uint64_t>) {
std::cout << "size_t == uint64_t" << std::endl;
} else {
std::cout << "size_t != uint64_t" << std::endl;
}
}
Result:
sizeof(size_t): 8
sizeof(uint64_t): 8
size_t != uint64_t
Compiler Info:
Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: arm64-apple-darwin21.6.0
Thread model: posix
Is there a reason why size_t
doesn't equal uint64_t
? If so, is there a particular mention in the standard of why this is so?
CodePudding user response:
Usually the type size_t
is an alias for the type unsigned long
.
From the C Standard (7.19 Common definitions <stddef.h>)
4 The types used for size_t and ptrdiff_t should not have an integer conversion rank greater than that of signed long int unless the implementation supports objects large enough to make this necessary.
Pay attention to that the rank of the type unsigned long int
is equal to the rank of the type signed long int
.
On the other hand, the type uint64_t
usually is defined as an alias for the type unsigned long long int
. Though that is implementation defined.
As for your code then the shown output means that sizeof( unsigned long int )
also is equal to 8 on the used system.
CodePudding user response:
- The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object ([expr.sizeof]).
- Recommended practice: An implementation should choose types for ptrdiff_t and size_t whose integer conversion ranks ([conv.rank]) are no greater than that of signed long int unless a larger size is necessary to contain all the possible values.