Error using else [closed]
want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 3 years ago .
improve this questionThe program is giving an error when compiling.
Else without a previous if
Something about the else
, has something wrong with the condition if
and else
?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char est_civil;
printf("Digite seu estado civil: ");
est_civil = getchar();
if (est_civil == 'C' || est_civil == 'c');
printf("Casado");
else
if (est_civil == 'S' || est_civil == 's');
printf("Solteiro");
else
return 0;
}
2 answers
-
The
if
s should not have a semicolon at the end The second
else
is empty. It needs to be removed.
The code can still be simplified, but the syntax errors are these.
The only thing I think important to change is to use a else if
instead of creating a else
Block with if
inside. This somewhat increases the readability of the code, perhaps it is interesting to see this publication*.
Something like:
if (est_civil == 'C' || est_civil == 'c')
printf("Casado");
else if (est_civil == 'S' || est_civil == 's')
printf("Solteiro");
Code fixed.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char est_civil;
printf("Digite seu estado civil: ");
est_civil = getchar();
if (est_civil == 'C' || est_civil == 'c')
printf("Casado");
else if (est_civil == 'S' || est_civil == 's')
printf("Solteiro");
return 0;
}
That's how it works, and much simpler, right?
#include <stdio.h>
int main() {
printf("Digite seu estado civil: ");
char est_civil = getchar();
if (est_civil == 'C' || est_civil == 'c') {
printf("Casado");
} else if (est_civil == 'S' || est_civil == 's') {
printf("Solteiro");
}
}
See working on ideone. E no repl.it. also I put on GitHub for future reference .
Never Fail to put keys on if
, unless you know what you're doing, which depends on a lot of experience. Especially don't put the ;
at the end of the condition of the if
because you are terminating it and nothing else will be executed as part of your block, it becomes innocuous except by side effect, which is advanced to its stage, and hardly anyone uses it even when it can make some sense.
if
is a command block. Blocks must be placed between keys. Even if eventually they can be omitted, and there are cases that can, so the compiler does not prevent, it should not do this to avoid unexpected errors. Without the keys you incur dangling else.
When it does not have nothing to do on a else
, do not use it. When what you have to do right after a else
other than a if
, Make a else if
and create a single block.
See more in What happens if I don't specify the { }?.