Can any one say why the break state does not work.

#include<stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    loop:
    scanf("%d",&n);
    if(n!=42){
    printf("%d",n);
    goto loop;}
   else
    {
    break;
    }
   
    return 0;
}

this is my code.

Dani AI

Generated

As already pointed out, the compiler error ("break statement not within loop or switch") happens because break is only valid inside a for, while, do-while loop or a switch. A plain label plus goto does not create a loop, so break is illegal there.

Two simple fixes:

  • Put the input logic inside a loop and use break to exit when you hit the sentinel value.
  • Or terminate the program from main (e.g., return) when the sentinel is seen.

Example (using C++ streams):

#include <iostream>

int main() {
    int n;
    while (std::cin >> n) {
        if (n == 42) break;   // valid: inside a loop
        std::cout << n << '\n';
    }
    return 0;
}

If you instead want to stop immediately from anywhere in main, return is the clean way; prefer it over std::exit in C++ because std::exit does not unwind the stack and will not call destructors for automatic (local) objects — see the docs for std::exit. The rules for break are documented here: break statement.

Quick troubleshooting: if a valid loop is present but the compiler still complains, check for mismatched braces that accidentally close the loop before the break, or for macros that change braces/keywords.

Recommended Answers

All 3 Replies

The error is .....
14 E:\codechef.cpp break statement not within loop or switch

You can only use break within a loop, or a switch. The C++ loops are for, while and do-while. You have no loop, so you cannot use break.

Oh! yea.
Thanks a lot.
I got it.
Ohhhh!!!!!!.

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.