Search code examples
c++types64-bitint64long-long

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


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?


Solution

  • 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.