if else statement

i cant figure out why my program isn't working. if i take out the "else" statement, then it runs fine. my error message says "illegal syntax. no matching if statement for else". my book shows an if-else just like i'm using it.

any ideas what im doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	//display information for searched account
	bool found = false;
	int find;
	while (!found) {
		cout << "Search for an account: ";
		cin >> find;
		for (int i=0; i<size; i++) {
			if (all[i].AcctNumber == find) 
				cout << "Account #" << find << " has a balance of $" << all[i].AcctBalance << endl;
				found = true;
			else
				cout << "Account not found. Please try again: "; 
		}
	}
Look at your if.
Where are the curly brackets that are necessary for multiple statements?
i had executive brackets (curly) after the if on line 8 but it didnt make a difference. i also tried with them after the else on line 11. im still getting the same error message. my initial reaction was that i didnt think i needed executive brackets in there anyway?
You need both.
You need a set of brackets surrounding the statements you bind to an if block if you want multiple lines. And yes you do need brackets.
This is correct:
1
2
3
4
5
6
7
 if (foo)
{
    foo = 1;
    foo = 2;
} // OPENING AND CLOSING BRACKETS BECAUSE THERE ARE MULTIPLE LINES OF CODE
else
    foo = 3; // NO BRACKETS BECAUSE THERE IS ONLY ONE LINE OF CODE 
Last edited on
wow, im an idiot...thank you very much tummychow!!!

so basically it's a rule to use executive brackets in an if statement any time you have more than one line of code in the statement? if i were to add a second line to the else statement, would the correct format be the following...

1
2
3
4
5
6
7
8
9
10
 if (foo)
{
    foo = 1;
    foo = 2;
} 
else
{
    foo = 3;
    foo = 4;
}
tummychow wrote:
NO BRACKETS BECAUSE THERE IS ONLY ONE LINE OF CODE

Oh my. You need curly brackets if there is more than one statement to execute. There could be more than one statement on a line. I recommend using it always, even if there is only one statement in the block.
tummychow, please try to post accurate answers, this way you only make more confusion.
Topic archived. No new replies allowed.