0

I'm confused because when I define a type from 1 to maxint in Pascal and I make the choice "0" which should return back to the repeat loop. Here is my code:

program Tanken;

type
tZahl = 1..maxint; 

var
tag1 : tZahl;
wahl : tZahl;
liter,
p : real;
BEGIN
repeat
    write ('Bitte Tag eingeben 1=Mon 2=Die 3=Mit 4=Don 5=Fre 6=Sam 7=Son: ');
    readln (tag1);
    writeln(tag1);
        
until tag1 <= 7;

    ....
end

This is how my constant, type and variable looks. Si I define tag1 as tZahl which should be from 1 to maxint but how ever when I run this at the first repeat loop when I type "0" it is accepted. I found this a bit confusing any ideas?

Saizzou
  • 58
  • 8

1 Answers1

2

To force type range checking at runtime you need to explicitly tell the compiler to with most used compilers by adding {$R+} to the top of the program.

However this will only throw a runtime error, which is not the input validation that you want. You will really need to program input validation yourself. E.g. by reading a string, and then converting it to a number using the VAL() procedure and checking the code argument for errors.

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
  • The function *Val* is not mentioned in ISO 7185 (Standard Pascal). Do you know which compilers support it? – August Karlstrom Nov 29 '20 at 10:17
  • Most Pascal use now uses Turbo Pascal/Delphi and compatibles (like Free Pascal). They all support it, though the exact type of the third parameter varies (word or longint). I don't know by heart what stdpascal uses for string->int conversion, too long ago, but I doubt that stdpascal defines "maxint", which is a typical Delphi/Object Pascal constant, so that question might be moot – Marco van de Voort Nov 29 '20 at 17:16
  • Most pascal implementations also seem to provide the variable *IOResult* as you mentioned in https://stackoverflow.com/questions/10052076/type-checking-in-pascal, so that would be an alternative. – August Karlstrom Nov 29 '20 at 17:35
  • Yes. But it requires turning of I/O checking locally with {$I-} and {$I+} which is even more compiler specific. But those are tricks of the trade, and I was trying to steer OP towards something that allows for more generalized robust input validation. – Marco van de Voort Nov 29 '20 at 17:47