Why am I getting an ‘Else without previous if’ error within a for loop?

else doesn’ take any condition, but you’ve written this:

else (charlieAlive == 1 && bobAlive == 0);  //else : (notice semicolon)

which doesn’t do what you intend it to do.

You want to do thos:

else if (charlieAlive == 1 && bobAlive == 0)  //else if : (semicolon removed)

Notice the difference.

Also, there can be at most one else block, associated with an if block Or a chain of if, else-if, else-if blocks. That is, you can write this:

if (condition) {}
else {}

Or,

if (condition0) {}
else if (condition1) {}
else if (condition2) {}
else if (condition3) {}
else if (condition4) {}
else {}

In any case, else block is always the last block. After that if you write another else block, that would be an error.

Apart from that you also have a semicolon at wrong place. Fixed that also:

else (charlieAlive == 1 && bobAlive == 0); <---- remove this semicolon!

Hope that helps.


Pick a good Introductory C++ Book. Here are few recommendations for all levels.

Leave a Comment