Hi,
I have this sample program where the compiler gives me error for the break statement.

The error is " misplaced break in afunction"

Could anyone help me understanding why the break statement gives an error? i understand that u can use break in a for , while loop etc., and exit early when required.

thanks for the help

#include <iostream.h> 

void afunction()
{ 
   if(1)
   {
     cout<<"Err";
     break;
   }
}

int main ()
{

  afunction();
}

break statements can be used in looping constructs, and in switch/case blocks. They cannot be used to break out of an "if" block, or as an alternative means of returning from a function.

Also, <iostream.h> is non-standard. #include <iostream> instead.

#include <iostream.h>

void afunction()
{
if(1)
{
cout<<"Err";
break;
}
}

int main ()
{

afunction();
}

and exit early when required.

I believe that by placing a break statement you were trying to return back to the main() function.
Placing a

return;//Instead of break might be what you are looking for

The above program just gives out an Err,
Probably because the above program is a 'test' program(or something of that sort)

This question has already been answered. Start a new discussion instead.