Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing char to Int in c++

in c++, is it okay to compare an int to a char because of implicit type casting? Or am I misunderstanding the concept?

For example, can I do

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

Or do we need to first convert it to an int?

so

 if(x < static_cast<int>(y)) 
{
 cout << "Your input is larger than x";
}
like image 391
user3029001 Avatar asked Dec 19 '22 16:12

user3029001


1 Answers

The problem with both versions is that you cannot be sure about the value that results from negative/large values (the values that are negative if char is indeed a signed char). This is implementation defined, because the implementation defines whether char means signed char or unsigned char.

The only way to fix this problem is to cast to the appropriate signed/unsigned char type first:

if(x < (signed char)y)

or

if(x < (unsigned char)y)

Omitting this cast will result in implementation defined behavior.

Personally, I generally prefer use of uint8_t and int8_t when using chars as numbers, precisely because of this issue.


This still assumes that the value of the (un)signed char is within the range of possible int values on your platform. This may not be the case if sizeof(char) == sizeof(int) == 1 (possible only if a char is 16 bit!), and you are comparing signed and unsigned values.

To avoid this problem, ensure that you use either

signed x = ...;
if(x < (signed char)y)

or

unsigned x = ...;
if(x < (unsigned char)y)

Your compiler will hopefully complain with warning about mixed signed comparison if you fail to do so.

like image 137
cmaster - reinstate monica Avatar answered Jan 02 '23 08:01

cmaster - reinstate monica