简体   繁体   中英

Is it good coding practice to exit a switch statement by calling a function with no intent to return

C newbie question. I have inherited C code that uses a switch statement to call functions as a means of exiting the switch. The called functions are not intended to return back into the switch statement unless there is POR or an access violation. The code after the switch is a while(1){} loop to prevent code run away (I guess).

Is this good coding practice? It seems that it if downstream code continues using functions to branch it would clutter the stack. Is there a better way to break out of switch statement when there is no intention to return afterwards?

The code works. However in website example code the switch statement is usually embedded in a while(1) loop where it is intended for the function to return to the switch statement.

switch(SYSRSTIV)
     {
     case SYSRST_NMIRST:
         reset_funtion(); //initialize hardware
         do_something1(); 
         break;
     case SYSRST_WDTPW:  
         pw_violation(); //Watchdog violation
         do_something2();
         break;
     case SYSRST_BOR:
         do_something3(); //normal operation
         break;
     default:
         do_something3();
      }


 while(1){ //trap if fall through
     set_error_flag();

 }
}

It's fine as long as you don't arrive at this very switch statement recursively and create infinite recursion. There's nothing special about the switch statement why you couldn't call an infinite loop from it.

Though having a single main loop and running the switch every iteration might result in more easily understandable code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM