c:if 没有 else
This error: 'else' without a previous 'if' is occurred when you use else statement after terminating if statement i.e. if statement is terminated by semicolon.
错误:如果在终止if语句后使用else语句(即if语句以分号终止),则会出现“ else”,而没有先前的“ if” 。
if...else statements have their own block and thus these statement do not terminate.
if ... else语句具有自己的块,因此这些语句不会终止。
Consider the given code:
考虑给定的代码:
#include <stdio.h>
int main()
{
int a = 10;
if(a==10);
{
printf("True\n");
}
else
{
printf("False\n");
}
return 0;
}
Output
输出量
prog.c: In function 'main':
prog.c:8:5: warning: this 'if' clause does not guard... [-Wmisleading-indentation]
if(a==10);
^~
prog.c:9:5: note: ...this statement, but the latter is misleadingly indented as if it is guarded by the 'if'
{
^
prog.c:12:5: error: 'else' without a previous 'if'
else
^~~~
How to fix?
怎么修?
See the statement, if(a==10);
参见语句if(a == 10);
Here, if statement is terminated by semicolon (;). Thus, Error: 'else' without a previous 'if' in C is occurred.
在此,if语句以分号( ; )终止。 因此,发生错误:C中没有先前的“ if”的“ else” 。
To fix the error remove the semicolon (;) after the if statement.
要解决该错误,请在if语句后删除分号( ; )。
Correct code:
正确的代码:
#include <stdio.h>
int main()
{
int a = 10;
if(a==10)
{
printf("True\n");
}
else
{
printf("False\n");
}
return 0;
}
Output
输出量
True
翻译自: https://www.includehelp.com/c-programs/else-without-a-previous-if-error-in-c.aspx
c:if 没有 else