Search code examples
overflowpascalprocedures

Pascal exit procedure when other one called


So my problem looks like, I have two procedures and they call each other but this can provide overflow. How to JUMP to procedure - like asm jmp not call? I don't want to use labels because I can't use GoTo between two different procedures. And I don't want the code which follows calling to a procedure to be executed. BTW, I use FPC.

unit sample;
interface

procedure procone;
procedure proctwo;

implementation

procedure procone;
begin
writeln('Something');
proctwo;
writeln('After proctwo'); //don't execute this!
end;

procedure proctwo;
begin
writeln('Something else');
procone;
writeln('After one still in two'); //don't execute this either
end;

end.

Solution

  • You'll have to use function parameter to indicate recursion so the function will know it's being called by related function. e.g.:

    unit sample;
    
    interface
    
    procedure procone;
    procedure proctwo;
    
    implementation
    
    procedure procone(const infunction : boolean);
    begin
      writeln('Something');
      if infunction then exit;
      proctwo(true);
      writeln('After proctwo'); //don't execute this!
    end;
    
    procedure proctwo(const infunction : boolean);
    begin
      writeln('Something else');
      if infunction then exit;
      procone(true);
      writeln('After one still in two'); //don't execute this either
    end;
    
    procedure usagesample;
    begin
      writeln('usage sample');
      writeln;
      writeln('running procone');
      procone(false);
      writeln;
      writeln('running proctwo');
      proctwo(false);
    end;
    
    end.
    

    When usagesample is called, it should produces this:

    usage sample
    
    running procone
    Something
    Something else
    After proctwo
    
    running proctwo
    Something else
    Something
    After one still in two