ravelinx ravelinx - 1 month ago 8
C Question

Can somebody explain me why is this C code not compiling my else if statement?

So I wrote this C code but cant find the bug of why is the compiler not getting the else if statement.

#include<stdio.h>

#define IN 1
#define OUT 0;

main() {
int c, nl, nw, nc, state;
c = nl = nw = nc = 0;

state = OUT;

while((c = getchar()) != EOF) {
++nc;

if(c == '\n')
++nl;

if(c == '\n' || c == '\t' || c == ' ')
state = OUT;
else if(state == OUT) {
state = IN;
++nw;
}
}

printf("%d %d %d\n", nl, nw, nc);

getchar();
}


I got an error saying "'else' without a previous 'if'"

Answer

As Jean-Fran├žois Fabre pointed out in the comments, your problem is the trailing semicolon in this #define:

#define OUT 0;

That causes your code to effectively look like this:

    if(c == '\n' || c == '\t' || c == ' ') 
        state = OUT;
    ;  // The "else" would go here, but you've already completed the "if"

    else if(state == OUT) {   // Now there is no "if" to associate with
        state = IN;
        ++nw;
    }

The preprocessor has the ability to cause all kinds of problems like this, which is a good reason to avoid it when possible. (This coming from a guy who has used cpp to do dirty, disgusting things).

In this case, an anonymous enum is the way to go:

enum {
    OUT = 0,
    IN = 1,
};

Also, this is a matter of style, but I always include curly braces, except for simple conditionals with no else:

// OK
if (ok)
    foo();

// Not OK
if (ok)
    foo();
else if (x == 3) {
    lots();
    of();
    stuff();
}
else
    bad();