Search code examples
c++typesintdifferencesigned

Difference between signed, signed int and int in C++?


Is there a difference between the datatypes of int, signed int and signed in C++?


And: If they would address all the same amount of space in memory (they would be equivalent in the context of memory-allocation), is there a performance difference in compile-/run-time between those (which of course would not be significant for programs like the following but when initializing several hundred variables of that type)?


I did a test with any of those to look for if there is any significant difference or any compiler warning or error:

With signed int:

#include <iostream>

int main()
{
    signed int a = 5;
    std::cout << "The number entered is " << a << std::endl;

    return 0;
}

With int:

#include <iostream>

int main()
{
    int a = 5;
    std::cout << "The number entered is " << a << std::endl;

    return 0;
}

With signed:

#include <iostream>

int main()
{
    signed a = 5;
    std::cout << "The number entered is " << a << std::endl;

    return 0;
}

The output is equivalent for all tests:

The number entered is 5

But that doesn't mean it has to be equal with regards to memory storage and performance.

Thanks in advance.


Solution

  • You can read about the rules for specifying integer types here.

    The first relevant rule is that if you don't provide either signed or unsigned the compiler assumes signed.

    signed - target type will have signed representation (this is the default if omitted)

    The other rule is that if you provide signed or unsigned and no size, int is assumed. So int, signed int and signed are functionally exactly equivalent.

    int - basic integer type. The keyword int may be omitted if any of the modifiers listed below are used.

    Edit : You can check the size of types in bytes using the sizeof operator (ex. sizeof(int) or sizeof(a)) and the range of values a numeric type can represent using std::numeric_limits (ex. std::numeric_limits<int>::max()).