Expected a statement after "else" condition

Hello! Need a small help here! The compiler is asking to give a statement after else statement. What should I write? I am returning "true" from a function if key is found.

1
2
3
4
5
6
7
8
9
10
11
12
	int key;
		cout << "Enter the key you want to search" << endl;
		cin >> key;
		if (ifNodeExists(root, key));
		{
			cout << "YES the key exists" << endl;
		}
		else
		{
			cout << "NO the key does not exists" << endl;
		}	
	}
Remove the semi-colon on line 4

Your current code is equivalent to:
1
2
3
4
5
6
7
8
9
10
11
12
13
		if (ifNodeExists(root, key))
		{
			// empty
		}

		{
			cout << "YES the key exists" << endl;
		}

		else  // else without if
		{
			cout << "NO the key does not exists" << endl;
		}
Last edited on
...
Last edited on
The semicolon ...

Your if-statement is: if ( ifNodeExists(root, key) ) ;
It could be written:
if ( ifNodeExists(root, key) ) {}

I other words, you have:
1
2
3
4
5
6
7
8
9
10
11
if ( ifNodeExists(root, key) ) {
    // nothing here
}

{
    cout << "YES the key exists" << endl;
}

else { // else without if
    cout << "NO the key does not exists" << endl;
}

Which can be further simplefied into
1
2
3
4
5
6
7
8
9
if ( ifNodeExists(root, key) ) {
    // nothing here
}

cout << "YES the key exists" << endl;

else { // else without if
    cout << "NO the key does not exists" << endl;
}



Remove the semi-colon.
Still giving an error! It says " Illegal else without matching if, expected a statement" (C2181)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int key;
		cout << "Enter the key you want to search" << endl;
		cin >> key;
		if (ifNodeExists(root, key))
		{
			// empty
		}
		{
			cout << "YES the key exists" << endl;
		}
		else  // else without if
		{
			cout << "NO the key does not exists" << endl;
		}
All you had to do was remove the semicolon at the end of the if statement. You didn't need to copy and paste bad code.
1
2
3
4
5
6
7
8
9
10
	cout << "Enter the key you want to search" << endl;
	cin >> key;
	if (ifNodeExists(root, key))
	{
		cout << "YES the key exists" << endl;
	}
	else
	{
		cout << "NO the key does not exists" << endl;
	}
Last edited on
Well, yes, of course. You've simply written out what people have told you was the wrong thing to do.

You didn't actually bother to read what people wrote, did you? You just saw that some people had posted code, and copied that code without making any effort to understand what people were saying, didn't you?
Thanks and sorry! The deadline was very near so was in a hurry! Sorry guys!
Topic archived. No new replies allowed.