I'm getting a warning message: overflow in implicit constant conversion.

1
2
3
4
5
6
char ch;
switch(ch)
  { 
    case 225:
       break;
  }


If I changed it to
1
2
  case (char)225:
    break;


will that behave as I expect it to? Or am I missing something going on underneath the hood that I should be aware about?

edit: I recently changed the compiler settings to pedantic, and this is the very last warning I'm getting. I'd like to be able to be completely rid of warnings, but don't want to fix what ain't broke. Should I change it or keep it as is?
Last edited on
In your implementation, char can only represent the range [-128;127]. Either:
1. Change the type of ch to unsigned char.
2. Use (unsigned char)ch as the switch expression.
3. Use -31 for the case expression (not recommended).
I don't think the cast will help with this warning. What the warning means is that one of your case statements is too large to fit in a character (>255 if your character is signed.) If you have values that are greater, I would copy ch (with a cast) to an integer variable and switch on that.
That is because a char, in your system, is represented as a byte, which can hold numerical values from -128 to 127. If you need greater values, use unsigned char (if you don't need negative values, of course, which is probably the case) or an int.
well case(char) 225: got rid of the warning message, but what I'm asking is did I create a possible logic error by doing this quick fix?
First of all, both helios and bbgst are right: I was thinking of unsigned char. Second of all I don't think it's a logic error: But using a type that is the correct size is both assured of making the compiler happy and is somewhat self-documenting, IMHO.
Yes, it's just a obscure way to do what you are trying to do. If you use unsigned char, you make your intention explicit, which is always the best thing to do.
Topic archived. No new replies allowed.