Apparent contradiction in using break and continue

I am confused as whether c++ permits the 'break' and 'continue'
commands to be used from an if statement. I see tutorials that allow it--
http://www.learncpp.com/cpp-tutorial/58-break-and-continue/

but I get an error when I try it on visual studio 2010. express compiler.
I get error = C2044 illegal continue; which then hitting F1 tells me that break and continue can only be used in do, while and for loops.
(And I guess switch statements.)

Thank you to anyone able to explain the apparent contradiction between tutorials and compiler.
We would like to see the code that causes this error, thank you.

EDIT: The compiler is, however, right. continues afaik can only be used in do, while, and for loops. They may also be used inside an if statement inside do, while, or for loops, but that's still inside the loop. ;)

-Albatross
Last edited on
This is just banged up, the actual code is too large, but the result is the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main()
{
	int a = 3;

if (a == 3){continue;}
	cout <<" Print this.\n";


	system ("pause");
	return 0;
}
Right, gotcha, thanks mate.
continue can only be used in loops. It begins the next iteration of the most inner loop. If you're not in a loop, then continuing doesn't make any sense (what exactly are you continuing?)

break is the same, except it escapes the most inner loop rather than iterating it. break can also be used to escape switch statements.
Thanks Disch, no worries now.
I just a had nested 'if' statements and just got myself confused.
Worked it out, thanks.
If it might help you, there's a way of breaking out of nested if statements. I assume you know about try, catch, and throw?

1
2
3
4
5
6
7
8
9
10
try
{
    if (something)
    {
        //A few ifs later
        throw false; //This gets you out.
       //A few brackets later
    }
}
catch (bool) {}


-Albatross
Last edited on
I wouldn't use exceptions for that.
I did read a bit about try,catch, throw, a while ago, but failed to catch on to its relevance at the time, and so promptly forgot all about it.
I was i fact going to ask whether there was actually a method of escaping if's. Thats good to know,
thanks, I shall go back and relearn try, catch and throw.
Exceptions are meant for error handling. That's their relevance. Listen to Disch.
Last edited on
Well. SLAGIATT. I could also think of a solution using loops or goto, if either seems like a better idea to you.

1
2
3
4
5
6
7
while(true)
{
    //Some ifs
    break;
    //Some brackets
break;
}



-Albatross
Last edited on
Topic archived. No new replies allowed.