Member Avatar for aiyer

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.

i thing break is for switch case statement only..

They're for abruptly "breaking" loops.

#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)

yeah, try using return instead...
*mumbles something about multiple exit points*

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.