Pascal-style case and C-style break lazarus / 62-General ---------------------------------------------------------------------- MarkMLl · 2022-09-29 10:06 In a number of circumstances C's ability to fall-through to the next case in a switch statement is useful, and there is the occasional newcomer to Pascal who complains that it is unsupported. Pascal does, obviously, have the break statement which can be used in a loop context, but I found myself wondering whether it had a convenient antithesis: it does, of course, which is constrained use of a goto. I have the code below in a procedure which is interpreting a message received via some form of serial connection. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TSerialThread.recvMessage(serHandle: TSerialHandle; var buffer: string;                                timeout, limit: integer): boolean;label  handleBcc; const  obeyTimeout= true;                    (* Normally true                        *) type  tRecvState= (expectSOH, expectAddress, expectSeq, expectCtrl, expectPayload,                              expectHandshake, expectOptionalEtx, expectBcc,                                                                  completed);...         expectOptionalEtx: if ch = ETX then begin                             buffer += ch;                           bccCount := BccLength;                             recvState := expectBcc (* To process next character *)                           end else begin                             bccCount := BccLength;                           recvState := expectBcc;{ Works }              goto handleBcc     (* To process current character *){ Fails } //              goto expectBcc     (* To process current character *)                         end;        expectBcc:     beginhandleBcc:                       if not (ch in ['!'..'~']) then                         break;                         buffer += ch;                         bccCount -= 1;                         if bccCount = 0 then                         recvState := completed                       end      otherwise        break                           (* Quite simply can't happen            *)      end  until obeyTimeout and Elapsed(limitTD, limit);  Using a goto is entirely natural in that context, and in my opinion it is difficult to criticise since it is actually /inhibiting/ the transfer of control to some distant part of the program (Dijkstra himself complained about religious application of his "considered harmful" suggestion). However, it does turn out to be necessary to declare a distinct label, simply using one of the label-like lines as the destination results in an "identifier isn't a label" error. Would it be feasible for the compiler to allow a goto to target a (numeric) destination in this situation? MarkMLl ---------------------------------------------------------------------- Zvoni · 2022-09-29 10:43 @Fallthrough: Huh? Just use consecutive If-Then with an Else-Clause for the last if If you need to exit the "switch" prematurely move the whole thing to a Function/Procedure @Goto in your sample: plain and simple: i avoid Goto like the plague. In a case like yours i'd rather use a (nested) Function/Procedure instead of Goto SomeLabel ---------------------------------------------------------------------- MarkMLl · 2022-09-29 10:49 Looking through code, I've not used goto /except/ in this context in about 20 years. I'm considering whether it would be possible to eliminate it- or more specifically the label declaration- from the language. MarkMLl ---------------------------------------------------------------------- 440bx · 2022-09-29 11:04 I've needed the C switch fallthrough feature a number of times and, since "goto"s are unequivocally unacceptable to me, I found a solution that implements the fallthrough C switch using a Pascal case statement without any need for a separate function and or procedure, no goto(s) either of course and, all inline as it should be (and as it is in C/C++) It's not quite as CPU efficient as the C switch but, for the extremely slight loss of performance, the construct is even more powerful and flexible than the C switch.   Jumps over C switches in a single case statement. Say NO to "goto" ---------------------------------------------------------------------- MarkMLl · 2022-09-29 11:19 Quote from: 440bx on September 29, 2022, 01:04:35 pmsince "goto"s are unequivocally unacceptable to me, Why? I quote Dijkstra on this: Quote"Please don't fall into the trap of believing that I am terribly dogmatical about [the goto statement]. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!" For the specific situation where it is shifting between the states of a state machine without soliciting further input I thing it's the lesser of the several possible evils. MarkMLl ---------------------------------------------------------------------- 440bx · 2022-09-29 11:28 Quote from: MarkMLl on September 29, 2022, 01:19:20 pmWhy? Because the target destination of a goto can be anywhere in the function/procedure.  IOW, its destination needs to be determined by searching for the target label (which can be anywhere in the function/procedure, not necessarily in the case statement, that's a problem.)  When a programmer reads a "goto xyz" statement, it provides no information whatsoever as to where the destination "xyz" is. Additionally, a goto, requires defining labels and manually keeping the labels "in synch" with the cases.  That's makes maintenance more difficult and error prone, not to mention that declaring a bunch of labels is tedious.  Pascal has enough deterministic control flow features to make the "goto" statement completely unnecessary, therefore a deficient solution. ---------------------------------------------------------------------- MarkMLl · 2022-09-29 11:53 Quote from: 440bx on September 29, 2022, 01:28:24 pmBecause the target destination of a goto can be anywhere in the function/procedure.  IOW, its destination needs to be determined by searching for the target label (which can be anywhere in the function/procedure, not necessarily in the case statement, that's a problem.)  When a programmer reads a "goto xyz" statement, it provides no information whatsoever as to where the destination "xyz" is. Additionally, a goto, requires defining labels and manually keeping the labels "in synch" with the cases.  That's makes maintenance more difficult and error prone, not to mention that declaring a bunch of labels is tedious.  Pascal has enough deterministic control flow features to make the "goto" statement completely unnecessary, therefore a deficient solution. Both of which I propose removing. MarkMLl ---------------------------------------------------------------------- PascalDragon · 2022-09-29 11:59 Quote from: MarkMLl on September 29, 2022, 12:06:47 pmWould it be feasible for the compiler to allow a goto to target a (numeric) destination in this situation? The goto statement can already target numeric destinations, however these need to be declared as a label nevertheless and that will stay, because Pascal is a language where things need to be declared before use. Also the branches of a case-statement are not labels, because they can be ranges as well and thus even if non-declared labels could be used you still can't target the branches of a case-statement with that. ---------------------------------------------------------------------- Warfley · 2022-09-29 11:59 C was developed for system development, and all the decisions in C must be viewed through this lens. The C switch-case statement is not an if-then-else replacement like in Pascal, it is a jumping table. This is why the case statement can only have a single value, and why you have the break. When entering a switch statement, it jumps to the case with the respective value and continues from there. When doing low level programming, jumping tables are essential, therefore this makes completely sense, and also in other development it can still be quite useful. For example when I worked on an emulator, that had many instructions with very similar effects, e.g. write to memory and increment and write to memory. In C this is simply: Code: C  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i switch (instr) {...case INC_STORE: reg++;case STORE:   memory[addr] = reg;  break;...}In Pascal it either requires nested ifs or goto. But the more high level you get, the less you need such constructs, so on a high level language (what Pascal most likely tries to be), I don't see the need for it. Especially as it is very confusing for many beginners, who learn C's switch case statements as "alternative to if- then-else" (which to be clear, it isn't and was never intendet to be, it's a jumping table, nothing more nothing less), and I had more than once to answer the question "My switch statement is broken". Because for some reason this jumping table concept somehow made it into languages like Java or C#, where you never need a jumping table ---------------------------------------------------------------------- 440bx · 2022-09-29 12:04 Quote from: MarkMLl on September 29, 2022, 01:53:55 pmBoth of which I propose removing. I am unclear as to what things you are proposing removing.  Can you be explicit on what they are ? Quote from: Warfley on September 29, 2022, 01:59:50 pmIn Pascal it either requires nested ifs or goto. It can be done in FPC/Delphi without if(s) and without goto(s) but, "lesser" forms of Pascal may require either or both. ---------------------------------------------------------------------- MarkMLl · 2022-09-29 12:18 Quote from: Warfley on September 29, 2022, 01:59:50 pmWhen doing low level programming, jumping tables are essential, Yes, and I have seen an ALGOL compiler which had several related variants (jump tables, format tables, substitution tables etc.) all of which had to be declared at the head of the program. To call it painful in an era where one can't just order a few extra printouts and spread them on a big desk is an understatement. MarkMLl ---------------------------------------------------------------------- jamie · 2022-09-29 20:54 I have ~ two pages of a single CASE statement using a GOTO loopback This process decodes a serial stream of digital data that can be incomplete with the current cached data and thus sets the GOTO loop to resume where it was.  Also, this large CASE plays the role of a C style switch whereas it changes the CASE switch to process to the next in line switch and uses a GOTO back to the loop, again.  If for some reason the current CASE index cannot be completed it just allows the case to exit as normal but keeps the current CASE index to pick up for the next time.  This logic was very hard to process using IF statements and the like, it was much easier using a C style Case switch. ---------------------------------------------------------------------- Thaddy · 2022-09-29 21:16 Quote from: MarkMLl on September 29, 2022, 02:18:43 pmjump tables, format tables, substitution tables You mean Birthday parties, Christmas tables and finding eggs in the garden? ---------------------------------------------------------------------- MarkMLl · 2022-09-30 06:58 Quote from: jamie on September 29, 2022, 10:54:56 pmI have ~ two pages of a single CASE statement using a GOTO loopback This process decodes a serial stream of digital data that can be incomplete with the current cached data and thus sets the GOTO loop to resume where it was.  Also, this large CASE plays the role of a C style switch whereas it changes the CASE switch to process to the next in line switch and uses a GOTO back to the loop, again.  If for some reason the current CASE index cannot be completed it just allows the case to exit as normal but keeps the current CASE index to pick up for the next time.  This logic was very hard to process using IF statements and the like, it was much easier using a C style Case switch. Yes, very much my rationale. In effect goto is overloading the selector value and going back to the start of the case: very much like continue does with a while. MarkMLl ---------------------------------------------------------------------- alpine · 2022-09-30 09:03 Quote from: MarkMLl on September 30, 2022, 08:58:22 amQuote from: jamie on September 29, 2022, 10:54:56 pmI have ~ two pages of a single CASE statement using a GOTO loopback This process decodes a serial stream of digital data that can be incomplete with the current cached data and thus sets the GOTO loop to resume where it was.  Also, this large CASE plays the role of a C style switch whereas it changes the CASE switch to process to the next in line switch and uses a GOTO back to the loop, again.  If for some reason the current CASE index cannot be completed it just allows the case to exit as normal but keeps the current CASE index to pick up for the next time.  This logic was very hard to process using IF statements and the like, it was much easier using a C style Case switch. Yes, very much my rationale. In effect goto is overloading the selector value and going back to the start of the case: very much like continue does with a while. MarkMLl BTW, I don't miss that particularity of the C-switch, besides one very special case of https://forum.lazarus.freepascal.org/index.php/topic,6 0218.msg450448.html#msg450448 With spending one more boolean: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     function TSerialThread.recvMessage(serHandle: TSerialHandle; var buffer: string;                                    timeout, limit: integer): boolean;    label      handleBcc;         const      obeyTimeout= true;                    (* Normally true                      *)         type      tRecvState= (expectSOH, expectAddress, expectSeq, expectCtrl, expectPayload,                                  expectHandshake, expectOptionalEtx, expectBcc,                                                                      completed);  done := false;  repeat case RecvState of         ...                 expectOptionalEtx: if ch = ETX then begin                               buffer += ch;                                 bccCount := BccLength;                                 recvState := expectBcc (* To process next character *)                               end else begin                                 bccCount := BccLength;                               recvState := expectBcc;                               continue;    { Works } //             goto handleBcc     (* To process current character *)    { Fails } //                goto expectBcc     (* To process current character *)                             end;            expectBcc:     begin    handleBcc:                           if not (ch in ['!'..'~']) then                             break;                             buffer += ch;                           bccCount -= 1;                             if bccCount = 0 then                               recvState := completed                         end          otherwise            break                         (* Quite simply can't happen            *)          end; done := true; until done;      until obeyTimeout and Elapsed(limitTD, limit);    Or, as Zvoni wrote, in that particular case with an extra check: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i      expectOptionalEtx, expectBcc:                              begin                              if (RecvState = expectOptionalEtx) then begin//           expectOptionalEtx: if ch = ETX then begin                               bccCount := BccLength;                               recvState := expectBcc;                                 if (ch = ETX) then begin                                   buffer += ch;                                 break;                                 end;                               end;//            expectBcc:     begin                             if not (ch in ['!'..'~']) then                             break;                             buffer += ch;                             bccCount -= 1;                           if bccCount = 0 then                               recvState := completed                           end          otherwise... ---------------------------------------------------------------------- MarkMLl · 2022-09-30 09:13 Quote from: y.ivanov on September 30, 2022, 11:03:13 amBTW, I don't miss that particularity of the C-switch, besides one very special case of https://forum.lazarus.freepascal.org/index.php/topic,60218.msg45044 8.html#msg450448 I don't miss it, since I'm only a C programmer rarely and under duress. However since dislike of the Pascal-style case statement has been a longstanding grumble among non-devotees, I found myself wondering what the opposite of (C-style) break would be since neither (Pascal-style) break nor continue can be used on account of their messing up a surrounding while or repeat, and at that point it occurred to me that certainly in my code this was about the only place that goto was being used. MarkMLl ---------------------------------------------------------------------- BeniBela · 2022-09-30 12:35 Quote from: PascalDragon on September 29, 2022, 01:59:41 pm The goto statement can already target numeric destinations, however these need to be declared as a label nevertheless and that will stay, because Pascal is a language where things need to be declared before use. Perhaps he meant with numeric goto that you could address the label indirectly Not this Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure huh;label 0,1,2;begin  goto 1;  0: writeln('a');  1: writeln('b');  2: writeln('c');end;  Not this Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure huh;label 0,1,2;var  i: Integer;begin  i := 1;  case i of  0: writeln('a');  1: writeln('b');  2: writeln('c');  end;end;  but this Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure huh;label 0,1,2;var  i: Integer;begin  i := 1;  goto (i);  0: writeln('a');  1: writeln('b');  2: writeln('c');end; ---------------------------------------------------------------------- Thaddy · 2022-09-30 12:46 Simply = without else.... ---------------------------------------------------------------------- MarkMLl · 2022-09-30 12:49 Quote from: BeniBela on September 30, 2022, 02:35:35 pmPerhaps he meant with numeric goto that you could address the label indirectly Yes, as in the example I posted when I started the thread. Also Sven makes the point that Quote...the branches of a case-statement are not labels, because they can be ranges as well and thus even if non-declared labels could be used you still can't target the branches of a case-statement with that. while I was musing on eliminating labels in their entirety and only using goto as the antithesis of (C-style) break in the context of a (Pascal-style) case statement. MarkMLl ---------------------------------------------------------------------- Zvoni · 2022-09-30 12:59 Quote from: y.ivanov on September 30, 2022, 11:03:13 amOr, as Zvoni wrote, in that particular case with an extra check: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i      expectOptionalEtx, expectBcc:                              begin                              if (RecvState = expectOptionalEtx) then begin//           expectOptionalEtx: if ch = ETX then begin                               bccCount := BccLength;                               recvState := expectBcc;                                 if (ch = ETX) then begin                                   buffer += ch;                                 break;                                 end;                               end;//            expectBcc:     begin                             if not (ch in ['!'..'~']) then                             break;                             buffer += ch;                             bccCount -= 1;                           if bccCount = 0 then                               recvState := completed                           end          otherwise...My statement was more along the lines of Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TSerialThread.recvMessage(serHandle: TSerialHandle; var buffer: string;                                timeout, limit: integer): boolean; const  obeyTimeout= true;                    (* Normally true                        *) type  tRecvState= (expectSOH, expectAddress, expectSeq, expectCtrl, expectPayload,                                expectHandshake, expectOptionalEtx, expectBcc,                                                                  completed);        Function FuncExpectBCC(Const Ach:Char;var AbccCount:Integer;var ArecvState:tRecvState):Boolean;        Begin                         Result:=False;                  if not (Ach in ['!'..'~']) then                 Exit(True);                buffer += ch;                AbccCount -= 1;                if AbccCount = 0 then                   ArecvState := completed;                              End; ........       expectOptionalEtx: if ch = ETX then begin                           buffer += ch;                             bccCount := BccLength;                             recvState := expectBcc (* To process next character *)                           end else begin                           bccCount := BccLength;                           recvState := expectBcc;                             If FuncExpectBCC(ch,bccCount,recvState) Then Break;                         end;        expectBcc:     If FuncExpectBCC(ch,bccCount,recvState) Then Break       otherwise        break                           (* Quite simply can't happen            *)      end  until obeyTimeout and Elapsed(limitTD, limit); No Goto or labels or other such nonsense ---------------------------------------------------------------------- alpine · 2022-09-30 13:29 Quote from: Zvoni on September 29, 2022, 12:43:50 pm@Fallthrough: Huh? Just use consecutive If-Then with an Else-Clause for the last if If you need to exit the "switch" prematurely move the whole thing to a Function/Procedure It is my misunderstanding, I thought you've meant to merge cases (the fall through case and the previous one) and then to use if-then to split them again in  the compound operator. ---------------------------------------------------------------------- PascalDragon · 2022-09-30 13:30 Quote from: BeniBela on September 30, 2022, 02:35:35 pmQuote from: PascalDragon on September 29, 2022, 01:59:41 pm The goto statement can already target numeric destinations, however these need to be declared as a label nevertheless and that will stay, because Pascal is a language where things need to be declared before use. Perhaps he meant with numeric goto that you could address the label indirectly I'm aware of what he meant. Which is why I added the part about the branches of the case-statement. ---------------------------------------------------------------------- Zvoni · 2022-09-30 14:54 Quote from: y.ivanov on September 30, 2022, 03:29:56 pmQuote from: Zvoni on September 29, 2022, 12:43:50 pm@Fallthrough: Huh? Just use consecutive If-Then with an Else-Clause for the last if If you need to exit the "switch" prematurely move the whole thing to a Function/Procedure It is my misunderstanding, I thought you've meant to merge cases (the fall through case and the previous one) and then to use if-then to split them again in  the compound operator. Ahhh….. ok, now i understand. Agreed. That is still my technique if i need fall-through. But any „fall-through“ scenario has to be coded very carefully (order of conditions etc.)