Search code examples
c++ctypestypeid

Differences between type definions and their meanings in typeid(equalizing)


unsigned int = unsigned

int = signed int = signed

signed long long int = singed long long = long long

unsigned long long int = unsigned long long

signed long int = signed long = long

unsigned long int = unsigned long

signed short int = signed short = short

unsigned short int = unsigned short

signed char = char

I'm wondering are the types i mentioned above same in C or C++ ? If it is, wondering their meanings while equalizing each other, would they be same again ? (EX: typeid(signed long int) == typeid(long))

Answer: http://cpp.sh/3rm


Solution

  • Some types are the same, some are distinct (=not the same):

    • for char, adding signed and unsigned gives you three distinct types in total.
    • for short, int, long and long long, signed is implied, and adding that does nothing. Adding unsigned will give you a new set of distinct types.
    • unsigned, short, long, and long long can be followed by int, but if the int is there or not does not give distinct types.

    In principle, the typeid of all the distinct types should be different. What this means is that template and function overload resolution will view these as different types, whereas e.g. passing a short and short int will both call the same overload.

    As far as I'm aware, these rules are the same for C and C++. If I made a mistake, please tell me, I'm writing this off the top of my head.

    To check this, you can use static_assert combined with std::is_same for a compile-time check:

    #include <type_traits>
    using std::is_same;
    
    static_assert(!is_same<char, signed char>(), "");
    static_assert(!is_same<char, unsigned char>(), "");
    static_assert(!is_same<unsigned char, signed char>(), "");
    
    
    static_assert( is_same<short, signed short>(), "");
    static_assert( is_same<int, signed int>(), "");
    static_assert( is_same<long, signed long>(), "");
    static_assert( is_same<long long, signed long long>(), "");
    
    static_assert(!is_same<short, unsigned short>(), "");
    static_assert(!is_same<int, unsigned int>(), "");
    static_assert(!is_same<long, unsigned long>(), "");
    static_assert(!is_same<long long, unsigned long long>(), "");
    
    static_assert( is_same<unsigned int, unsigned>(), "");
    static_assert( is_same<short int, short>(), "");
    static_assert( is_same<long int, long>(), "");
    static_assert( is_same<long long int, long long>(), "");
    
    int main(){} // only included to make the program link
    

    Live demo here.