Home > Backend Development > C++ > body text

How to Break Out of a Loop from Within a Switch Statement in C ?

Patricia Arquette
Release: 2024-10-28 12:13:31
Original
135 people have browsed it

How to Break Out of a Loop from Within a Switch Statement in C  ?

Breaking Out of Loops from Within a Switch Statement

While navigating through code, situations may arise where you need to exit a loop from within a switch statement. Consider the following scenario:

<code class="cpp">while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        **HERE, break out of the loop itself**
    }
}</code>
Copy after login

The goal is to find an elegant way to break out of the enclosing loop without resorting to flags or conditional breaks.

A Swift Exit: Using 'goto'

In the realm of C , the 'goto' statement provides a straightforward solution. It allows you to jump to a specific label within the current function. By leveraging 'goto,' you can cleanly exit the loop from within the switch statement:

<code class="cpp">while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;</code>
Copy after login

This approach offers a concise and explicit way to terminate the loop. Keep in mind that 'goto' should be used sparingly to maintain code readability. However, in certain situations, it can provide a simple and effective solution.

The above is the detailed content of How to Break Out of a Loop from Within a Switch Statement in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!