Thursday, February 25, 2010

Non-Printable Char to int Conversion Issue in C

Current post is on non-printable character conversion to int issue in C language.


By the topic you will assume, what is this? Even a C student who has just started will know that, there is no harm, as we are upgrading the type from character (char) to integer (int).

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

Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.