If on my machine sizeof(long) == sizeof(long long), why aren't they the same type?

4.5k views Asked by At

If I run:

#include <type_traits>
#include <iostream>

int main()
{
    std::cout << "sizeof(long) = " << sizeof(long) << "\n";
    std::cout << "sizeof(long long) = " << sizeof(long long) << "\n";
    std::cout << "std::is_same<long, long long>::value = " 
        << std::boolalpha << std::is_same<long, long long>::value 
        << "\n";
    return 0;
}

on my machine (and on Coliru), I get:

sizeof(long) = 8
sizeof(long long) = 8
std::is_same<long, long long>::value = false

And it isn't just std::is_same<>; translation units expecting an instantiation for int64_t fail because I only compiled for int and long long int in another translation unit, despite it all happening on the same machine.

Why aren't these types the same? I mean, exhibiting behavior like you would have from typedef's of the same type?

2

There are 2 answers

5
Bathsheba On BEST ANSWER

It's the language rule and crucial for portability.

int, long, and long long are all treated as different types by the language, even if they have the same number of bytes and complement scheme.

This is intentional. It means that you can write code that can compile on different platforms where the size of the types vary.

It would be very annoying if say for example, two overloads

void foo(int f)

and

void foo(long f)

were treated as the same function on one platform, and different overloads on another.

2
Omnifarious On

Similarly, this program:

#include <type_traits>
#include <iostream>

int main()
{
    using ::std::cout;
    using ::std::is_same;
    using ::std::boolalpha;

    cout << "sizeof(long) = " << sizeof(long) << "\n";
    cout << "sizeof(long long) = " << sizeof(long long) << "\n";
    cout << "sizeof(double) = " << sizeof(double) << "\n";
    cout << "::std::is_same<long, long long>::value = " 
        << boolalpha << is_same<long, long long>::value 
        << "\n";
    std::cout << "::std::is_same<long, double>::value = " 
        << boolalpha << is_same<long, double>::value 
        << "\n";
    return 0;
}

outputs this:

sizeof(long) = 8
sizeof(long long) = 8
sizeof(double) = 8
::std::is_same<long, long long>::value = false
::std::is_same<long, double>::value = false

As you can see, double and long appear to be the same length, why aren't they just typedefs of the same type?