在c ++中比较char到Int

use*_*001 4 c++ int types casting char

在c ++中,由于隐式类型转换,可以将int与char进行比较吗?还是我误解了这个概念?

例如,我可以吗

int x = 68;
char y;
std::cin >> y;
//Assuming that the user inputs 'Z';
if(x < y) 
{
 cout << "Your input is larger than x";
}
Run Code Online (Sandbox Code Playgroud)

或者我们是否需要先将其转换为int?

所以

 if(x < static_cast<int>(y)) 
{
 cout << "Your input is larger than x";
}
Run Code Online (Sandbox Code Playgroud)

cma*_*ter 5

这个问题版本是,你不能肯定是从负/大值(如果是负的值所得的值char确实是signed char).这是实现定义的,因为实现定义了char手段signed char还是unsigned char.

解决此问题的唯一方法是首先转换为适当的signed/unsigned char类型:

if(x < (signed char)y)
Run Code Online (Sandbox Code Playgroud)

要么

if(x < (unsigned char)y)
Run Code Online (Sandbox Code Playgroud)

省略此强制转换将导致实现定义的行为.

就个人而言,我通常更喜欢使用uint8_tint8_t使用字符作为数字,正是因为这个问题.


这仍然假设该值在您平台上(un)signed char的可能int值范围内.如果sizeof(char) == sizeof(int) == 1(仅当a char为16位时可能!),并且您正在比较有符号和无符号值,则可能不是这种情况.

要避免此问题,请确保使用其中任何一个

signed x = ...;
if(x < (signed char)y)
Run Code Online (Sandbox Code Playgroud)

要么

unsigned x = ...;
if(x < (unsigned char)y)
Run Code Online (Sandbox Code Playgroud)

如果你没有这样做,你的编译器会抱怨有关混合签名比较的警告.