I have a question about using goto statements in C ++. I understand that this topic is controversial and I am not interested in any broad tips or arguments (I usually deviate from using goto ). Rather, I have a specific situation and I want to understand if my solution, which uses goto instructions, is good or not. I would not call myself new to C ++, but I would not classify myself as a programmer on a professional level. The part of the code that raised my question rotates in an infinite loop after starting. The overall stream stream in pseudo-code is as follows:
void ControlLoop::main_loop() { InitializeAndCheckHardware(pHardware) //pHardware is a pointer given from outside //The main loop while (m_bIsRunning) { simulated_time += time_increment; //this will probably be += 0.001 seconds ReadSensorData(); if (data_is_bad) { m_bIsRunning = false; goto loop_end; } ApplyFilterToData(); ComputeControllerOutput(); SendOutputToHardware(); ProcessPendingEvents(); while ( GetWallClockTime() < simulated_time ) {} if ( end_condition_is_satisified ) m_bIsRunning = false; } loop_end: DeInitializeHardware(pHardware); }
The pHardware pointer is passed from outside the ControlLoop object and has a polymorphic type, so it makes no sense for me to use RAII and create and destroy the hardware interface itself inside main_loop. I believe that I could have pHardware create a temporary object that is a "session" or "use" of hardware that could be automatically cleared when I exit main_loop, but I'm not sure if this idea will become more clear to anyone otherwise I intend. There will be only three exits from the cycle: firstly, if bad data is read from external equipment; the second is if ProcessPendingEvents () indicates an interrupt initiated by the user, which simply causes m_bIsRunning to become false; and the last - if the final condition is satisfied at the bottom of the cycle. Perhaps I should also note that main_loop could be started and completed several times during the duration of the ControlLoop object, so after that it should exit using m_bIsRunning = false .
Also, I understand that I could use the break keyword here, but most of these pseudo-code calls inside main_loop are not actually encapsulated as functions, simply because they will need to have many arguments, or they all need access to member variables. In my opinion, both of these cases would be more confusing than just leaving main_loop as a longer function, and because of the length of the large while loop, an expression like goto loop_end seems to me more understandable.
Now to the question: will this solution be inconvenient for you if you have to write it in your own code? This seems a bit wrong to me, but then I never used the goto statement before in C ++ code, so my request for help is from experts. Are there any other basic ideas that I'm missing to make this code clearer?
Thanks.
source share