Break inside curly brackets?

Hi,
I have a bug in this piece of code, i.e. it executes once then hangs.
It's part of a CNC sketch for my bench drill.
I use a TV remote for a keypad.

My question: is it OK to put a break (line 5) inside curly backets, & not uniquely at the end of the case?
Is a better alternative to use endif instead of if on line 7?

TIA

Diksan

    case 2192:  //Ch- key
      if (simul == HIGH) {
        Serial.println(F("Simul!"));
        blinkBL(3);
        break;
      }
      if (drill_state == 3) {  //drill 1 hole if unloaded
        lcd.setCursor(0, 2);
        lcd.print(F("                    "));
        lcd.setCursor(0, 1);
        lcd.print(F("**  Drill 1 hole  **"));
        Serial.println("Drill 1 hole");
        while (Zposition <= Zdownposition) Zstep_down();
        showXYZ();
        while (Zposition > Zupposition) Zstep_up();
        showXYZ();
      } else {
        Serial.println(F("Can't drill yet! Unload, set Z zero, drill up (C) & down (D)"));
        blinkBL(3);
      }
      break;


It's ok, yes, if a little non-conventional. If I saw this I might wonder if a "case xxx" line had been accidentally deleted.

Not sure what you mean here, endif is not a C keyword.

Using an if structure would be equally clear and more conventional IMO.

erratum: else if, not endif. My bad!

#endif is related to #ifdef and #if, not with if.

#endif. #ifdef and #if are preprocessor statements and are applied at compile time influencing what part of a code will be compiled, not at runtime.

That will work if it suites your needs.

There's a style thing that says return should appear once in a function, at the end.

Sometimes doing this makes thing less clear or necessitates code convolutions.

I think the same might be said about break. Here else if is easy enough to do, and allows staying with the same convention.

I've not seen that hammered on like is done to seeing return all over the place.

a7

That depends on what you want the code to do! It will make it behave differently. If simul is not HIGH, do you still want the code to check drill_state ? If not, is that what the extra break is for? In that case, removing the extra break and using else if would be a better way to structure the code in my opinion.

You can't avoid using break in switch-case statements in C. But apart from that, I would recommend keeping use of break to an absolute minimum. Same goes for return.

I changed the code to use else if. No more bug!

I will now check to see if there are any more of these in the sketch :wink:

Dick-san

There was nothing wrong with the original snippet you posted. The "bug" was elsewhere in the code that you didn't post. So, what ever changes you made either fixed it somewhere else or simply masked it to reappear later.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.