C++: char类型既不是signed char也不是unsigned char

对于 int, short, long, long long 类型, 增加 signed, 类型不变。

对于 char 类型, 增加 signed, 类型变了。 char 既不是 signed char, 也不是 unsigned char。
虽然 char 的取值范围, 一定是:要么是 signed char 范围, 要么是 unsigned char 范围。

Unlike the other integer types, there are three distinct basic character types: char, signed char, and unsigned char. In particular, char is not the same type as signed char. Although there are three character types, there are only two representations: signed and unsigned. The (plain) char type uses one of these representations. Which of the other two character representations is equivalent to char depends on the compiler.

如下代码在 Apple Clang 15.0.0 下运行

#include <iostream>
#include <type_traits>

template<typename T>
void hello()
{
    std::cout << "hello<T>" << std::endl;
}

template<>
void hello<int>()
{
    std::cout << "hello<int>" << std::endl;
}

template<>
void hello<signed char>()
{
    std::cout << "hello<signed char>" << std::endl;
}

template<>
void hello<unsigned char>()
{
    std::cout << "hello<unsigned char>" << std::endl;
}

int main()
{
    std::cout << std::boolalpha;
    
    std::cout << "int is signed int? " << std::is_same<int, signed int>::value << std::endl;
    std::cout << "short is signed short? " << std::is_same<short, signed short>::value << std::endl;
    std::cout << "long is signed long? " << std::is_same<long, signed long>::value << std::endl;
    std::cout << "long long is signed long long? " << std::is_same<long long, signed long long>::value << std::endl;

    std::cout << "char is signed char? " << std::is_same<char, signed char>::value << std::endl;
    std::cout << "char is unsigned char? " << std::is_same<char, unsigned char>::value << std::endl;

    std::cout << "------------\n";
    std::cout << "hello<int>() is "; hello<int>();
    std::cout << "hello<signed char>() is "; hello<signed char>();
    std::cout << "hello<unsigned char>() is "; hello<unsigned char>();
    std::cout << "hello<char>() is "; hello<char>();

    return 0;
}

// result:
// int is signed int? true
// short is signed short? true
// long is signed long? true
// long long is signed long long? true
// char is signed char? false
// char is unsigned char? false
// ------------
// hello<int>() is hello<int>
// hello<signed char>() is hello<signed char>
// hello<unsigned char>() is hello<unsigned char>
// hello<char>() is hello<T>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值