ADVERTISEMENT
ADVERTISEMENT

Error: 'else' without a previous 'if' in C

Here, we will learn where an error: 'else' without a previous 'if' is occurred and how to fix in C programming language?
Submitted by IncludeHelp, on September 01, 2018

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 statements have their own block and thus these statement do not terminate.

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
     ^~~~
ADVERTISEMENT

How to fix?

See the statement, if(a==10);

Here, if statement is terminated by semicolon (;). Thus, Error: 'else' without a previous 'if' in C is occurred.

To fix the error remove the semicolon (;) after the if statement.

Correct code:

#include <stdio.h>

int main()
{
	int a = 10;
	if(a==10)
	{
		printf("True\n");
	}
	else
	{
		printf("False\n");
	}

	return 0;
}

Output

True

C Common Errors Programs »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.