Search code examples
cif-statementwhile-loopgetchar

Why does it not work to use multiple "if"s but it does work to use "if"s and "else if"s inside a while loop?


This was my code without using else if:

#include <stdio.h>

main()
{
    long s = 0, t = 0, n = 0;
    int c;
    while ((c = getchar()) != EOF)
        if (c == ' ')
            ++s;
        if (c == '\t')
            ++t;
        if (c == '\n')
            ++n;
    printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}

This is the code using else if:

#include <stdio.h>

main()
{
    long s = 0, t = 0, n = 0;
    int c;
    while ((c = getchar()) != EOF)
        if (c == ' ')
            ++s;
        else if (c == '\t')
            ++t;
        else if (c == '\n')
            ++n;
    printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}

For a reason, not using the else if doesn't work. What is the reason? I know that using if does it one by one while using else if stops at the first statement that is true. This has a difference in performance. Anyhow not using else if in this particular (if not other) while loop doesn't seem to work.

Thanks.


Solution

  • Correctly indented, your first program looks like this:

    #include <stdio.h>
    
    main()
    {
        long s = 0, t = 0, n = 0;
        int c;
        while ((c = getchar()) != EOF)
            if (c == ' ')
                ++s;
        if (c == '\t')
            ++t;
        if (c == '\n')
            ++n;
        printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
    }
    

    The body of a while loop is a single statement.

    if ... else if ... else if ... else all forms one big statement. By separating your conditions into several statements (if, if, if), you've moved all but the first one out of the while loop.

    To avoid this problem, always use a compound statement (i.e. a block: { ... }) as the body of a while or if statement.

    By the way, main() hasn't been valid C since 1999. It should be int main(void).