Except for
bool
and the extended character types, the integral types may be signed or unsigned (34 pp. C++ Primer 5ed)
"may be", makes me confused, however, please don't give such answer, I'm not asking the difference between, for example, int
and unsigned int
when you explicitly write them down in the declaration. I would like to know for type char, short, int, long, long long
under what condition it is singed or unsigned
I've write a simple test code on my Mac and compiled by GNU compiler, it tells, the char
is singed
#include <iostream>
#include <limits>
using namespace std;
int main( int argc, char * argv[] )
{
int minChar = numeric_limits<char>::min();
int maxChar = numeric_limits<char>::max();
cout << minChar << endl; // prints -128
cout << maxChar << endl; // prints 127
return 0;
}
The same mechanism was applied to all of the sign-able integral types, and the results are shown below.
minOfChar: -128
maxOfChar: 127
minOfShort: -32768
maxOfShort: 32767
minOfInt: -2147483648
maxOfInt: 2147483647
minOfLong: 0 // This is interesting, 0
maxOfLong: -1 // and -1 :p
minOfLongLong: 0 // shouldn't use int to hold max/min of long/long long #Bathsheba answered below
maxOfLongLong: -1 // I'll live this error unfixed, that's a stupid pitiful for newbies like me, also good for leaning :)
The result tells me, for char, short, int, long, long long
which is compiled by g++ on a Mac, are singed integers by default.
So the question is as the title says:
What decides an integral type is singed or unsigned
Aside from char
, the signedness of the integral types is specified in the C and C++ standards, either explicitly, or by a simple corollary of the ranges that the types are required to implement.
The signedness of char
is determined by the particular implementation of C and C++; i.e. it's typically up to the compiler. And the choice will be made to best suit the hardware.
Note that char
, signed char
, and unsigned char
are all distinct types, much in the same way that int
and long
are distinct types even if they have the same size and complementing scheme.
It's also not a particularly good idea to assign, for example,
numeric_limits<long>::min();
to an int
value, the behaviour of this could be undefined. Why not use
auto foo = numeric_limits<whatever>::min();
instead?