是什么决定一个整数类型默认是有符号的还是无符号的?

What decides an integral type is singed or or unsigned by default?

Except for bool and the extended character types, the integral types may be signed or unsigned (34 pp. C++ Primer 5ed)

"may be",弄得我很迷糊,不过请不要给这样的answer,我不是问的区别,比如, intunsigned int 当您在声明中明确写下它们时。我想知道类型 char, short, int, long, long long 在什么条件下它是 singed 或 unsigned

我在我的 Mac 上写了一个简单的测试代码,并由 GNU 编译器编译,它告诉我,char 被烧焦了

#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;
}

相同的机制应用于所有可签名的整数类型,结果如下所示。

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 :)

结果告诉我,g++在Mac上编译的char, short, int, long, long long默认是单数整数。

所以问题如题所示:

决定整型是有符号还是无符号的

除了 char 之外,整数类型的符号在 C 和 C++ 标准中明确指定,或者通过类型需要实现的范围的简单推论指定。

char 的符号由 C 和 C++ 的特定实现决定;也就是说,这通常取决于编译器。并且将做出最适合硬件的选择。

请注意 charsigned charunsigned char 都是 不同的 类型,与 intlong 是不同的类型,即使它们具有相同的大小和互补方案。

分配也不是一个特别好的主意,例如,

numeric_limits<long>::min(); 

int 值,其行为可能未定义。为什么不使用

auto foo = numeric_limits<whatever>::min();

代替?