0

I have the following code:

#include <stdio.h>
#include <ctype.h>

int main(int argc, char **argv)
{
        int ch, lower, upper = 0;
        printf("Enter a line of text: \n");
        while ((ch = getchar()) != EOF) {
        if (islower(ch)) {
                ch = toupper(ch);
                ++upper;
        } else if (isupper(ch)) {
                ch = tolower(ch);

                printf("Looking at lower: %d\n", lower);
                ++lower;
                printf("Looking at lower: %d\n", lower);
        }
        putchar(ch);
        }
        printf("Hello\n");
        printf("\nRead %d characters in total. %d converted to upper-case, %d to lower-case.", upper+lower, upper, lower);
}

For some reason the upper variable is being set correctly, but can't work out why lower is giving an erroneous value. E.g. If I type in 'Football' it says 4195825 converted to lower-case, where the actual output should be 1.

I can't see where I'm going wrong here.

1 Answer 1

3

You haven't initialized lower. It's value is indeterminate.

C11: 6.7.9 Initialization (p10):

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

Initialize it to 0.

int ch, lower = 0, upper = 0;  
Sign up to request clarification or add additional context in comments.

6 Comments

I don't think that's the issue. If I do int ch, lower, upper; It gives the same output.
Yes this is the issue. I quoted the standard.
Oh sorry yeah you are right, but how come the upper variable works correctly if I do int ch, lower, upper; but the lower variable does not?
Indirectly, your program invokes undefined behavior. You may either get expected or unexpected output. Nothing can be said.
Interesting.. is there anywhere I can read more about this random behaviour?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.