1

In my original code I had this:

if (isupper(text[i]) == true)
            {
              int j = (int) text[i] % 65;
              int k = (j + key) % 26;
              char l = (char) k + 65;
              printf("%c\n", l);
            }

and whenever I ran it, it skipped over this block, even though the condition was met. However, after one small modification (see below) it worked.

if (isupper(text[i]))
            {
                int j = (int) text[i] % 65;
                int k = (j + key) % 26;
                char l = (char) k + 65;
                printf("%c", l);
            }

Why is this the case?

3

The isupper() function (and all of it's cousins) returns an int, not a bool. Depending on which function call (isalpha, isfloat, isupper, islower, etc.) is invoked, an integer that is a power of 2 will be returned when the function is supposed to return true, and will ALWAYS return 0 when returning false.

With that in mind, you need to understand exactly what those two statements mean and how an integer is interpreted as a bool.

First, remember that 0 is always interpreted as false. A non-zero integer (even a negative) is interpreted as true.

Now, going the other way, true is interpreted as 1 and only 1. False is always interpreted as 0.

So let's look at the two if statements.

if (isupper(text[i]) == true)

The isupper() function happens to return 256 when true. The statement will evaluate the isupper call as 256, then will evaluate true as 1, and finally will compare 256 == 1, which is false. The problem here should now be obvious. (It's also a common mistake for new programmers. )

Now look at the other version.

 if (isupper(text[i]))

This evaluates isupper()'s result as 256. It then evaluates 256 as true or false. Since it's a non-zero int, it evaluates as true.

Now that you see what actually happens, step-by-step, does it make sense?

When using any of the functions in this family, always just use the function call and never compare to true. Also, make sure that you always understand the return values of function calls that you use.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .