LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   why gcc complained "‘else’ without a previous ‘if’" (http://www.linuxquestions.org/questions/programming-9/why-gcc-complained-%91else%92-without-a-previous-%91if%92-4175443524/)

hunter_king 12-30-2012 10:37 PM

why gcc complained "‘else’ without a previous ‘if’"
 
hi all:
i wrote a very simple C code, but when i Compiled, gcc Complain that "error: ‘else’ without a previous ‘if’". here'is the code
Code:

#define TRUE 1
#define FALSE 0

int compare (char opt_1, char opt_2)
{
        if (opt_1 == '*' || opt_1 == '/')
                return TRUE;
        else
                return FALSE;
}


business_kid 12-31-2012 05:01 AM

It obviously sees a problem with the if. placing of punctuation is vital.

I'm on a deferred year and unable to check mysefl. Is it if . . .else or if. . . then . . . else?

dwhitney67 12-31-2012 06:17 AM

Quote:

Originally Posted by hunter_king (Post 4859793)
hi all:
i wrote a very simple C code, but when i Compiled, gcc Complain that "error: ‘else’ without a previous ‘if’".

There's nothing wrong with the code you posted; if GCC is indeed spewing an error, then it lies elsewhere.

NevemTeve 12-31-2012 06:54 AM

You've misunderstood something. I tried it, and got only a warning:

Code:

hunter_king.c: In function 'compare':
hunter_king.c:4: warning: unused parameter 'opt_2'


linosaurusroot 12-31-2012 08:52 AM

As it happens in this example the "else" is unnecessary.
Code:

if (opt_1 == '*' || opt_1 == '/')
    return TRUE;

return FALSE;


johnsfine 12-31-2012 09:17 AM

Quote:

Originally Posted by hunter_king (Post 4859793)
here'is the code

Since that code wouldn't give the error you described, I assume you simplified the actual code before posting (often a good practice) but failed to retest the simplified code to make sure it had the same error as the original (clearly a bad practice).

Consider this incorrect program similar to what you posted. With some compiler, I think it would give the error you reported (though with my copy of gcc it gives a different error). I'm intending this to show that the difference between what you posted and what you tested might be subtle.
Code:

#define TRUE 1;
#define FALSE 0;

int compare (char opt_1, char opt_2)
{
        if (opt_1 == '*' || opt_1 == '/')
                return TRUE;
        else
                return FALSE;
}



All times are GMT -5. The time now is 05:47 PM.