Current post is on non-printable character conversion to int issue in C language.
However, many people including the advanced programmer do not know is that: “conversion of character having non-printable value to int is machine dependent”.
It means that if you take a variable:
char mynonprintablechar = 129;
And then you try to upgrade to int implicitly, the results which you get, will make you scratch your hair.
Example 1: If - Else Statement
if( mynonprintablechar == 129)
printf(“You expected me”);
else
printf(“You may get me”);Example 2: Switch Statement
switch(mynonprintablechar)
{
case 129:
printf(“You expected me”);
break;
default:
printf(“You may get me”);
}
The solution:
1. Have unsigned char as variable type.
2. downcast the int against which you compare to char.
3. cast as unsigned char.
Do drop me a mail, if I saved you from scratching your hair :)
No comments:
Post a Comment