why long long is not int64_t but they have same size?

3.1k Views Asked by At

I tried this on my computer

std::cout << std::is_same<int64_t, long long>::value;
std::cout << std::is_same<int64_t,  long>::value;
std::cout << sizeof(long);
std::cout << sizeof(long long);
std::cout << sizeof(int64_t);

and the result is false, true, 8, 8, 8

I know int64_t is exactly 64 bit, and it shows long is same as int64_t, but long long is different from int64_t and it is also 64bit. Why could this happen?

EDIT

Can I use long long and int64_t interchangeably on my machine, given that they are both integer types and have same size?

2

There are 2 best solutions below

0
On BEST ANSWER

long and long long are built-in types defined by the core language.

int64_t is defined by the <cstdint> header (in practice include <stdint.h>). It's defined as an alias for some built-in type. In your case it's defined as an alias for long.


Built in types that can be the same size on some platform still need to be regarded as distinct types in order to not create ambiguous calls of overloaded functions.

There are even built in numerical types that guaranteed have the same size and signedness, but still are distinct. Namely, all three of unsigned char, char and signed char are distinct and of size 1, but char must be the same signedness as one of the others. Although I don't recommend doing it, technically you can freely overload functions based on just this difference.


Re

Can I use long long and int64_t interchangeably on my machine, given that they are both integer types and have same size?

That depends on what you mean by “interchangeably”.

Since int64_t with your compiler is an alias for long, you can't call a function expecting an int64_t*, with a long long* pointer.

But long long is guaranteed to be at least 64 bits, and in this sense it's only with respect to readability that it matters which of long long and int64_t you choose.

1
On

3.9.1

There are five standard signed integer types : “signed char”, “short int”, “int”, “long int”, and “long long int"

[18.4.1] of the same says that

using int64_t = signed integer type ; // optional

So you are looking at two distinct basic types and comparing them to the type alias. In your case its int64_t is aliased with long however there could be an implementation when its aliased with long long int


As for you extra question, it depends what do you mean by interchangeability, long long is at least as long as a long but in theory or in future could be 'longer', using these types interchangeably would still required type casting