Recent

Author Topic: Why is an enumeration out of range error not cought compile time  (Read 964 times)

Anonimista

  • New Member
  • *
  • Posts: 19
Why is an enumeration out of range error not cought compile time
« on: September 11, 2019, 08:53:44 pm »
I have this code:

Code: Pascal  [Select][+][-]
  1. program project1;
  2.  
  3. type
  4.     shape = (rectangle, square, ellipse, circle);
  5.     color = (red, yellow, green);
  6.     sex = (male, female);
  7.  
  8. var
  9.     s: sex;
  10.     c: color;
  11.  
  12.  
  13. begin
  14.  
  15.     s := male;
  16.     writeln(s);
  17.     writeln(succ(s));
  18.     { writeln(pred(s)); -- Runtime error 107 }
  19.     writeln(ord(pred(s)));
  20.  
  21.     c := red;
  22.     writeln(c);
  23.     writeln(succ(c));
  24.  
  25.     readln;
  26.  
  27. end.

The error is "Invalid enumeration
    Reported when a text representation of an enumerated constant cannot be created in a call to str or write(ln)."

Can anybody explain why this error is not caught at compile time. Is it to keep the compiler simple?

jamie

  • Hero Member
  • *****
  • Posts: 6090
Re: Why is an enumeration out of range error not cought compile time
« Reply #1 on: September 11, 2019, 09:15:11 pm »
Delphi help says not to use a PRED on a WRITE operation because WRITE does not have a way to translate it to something usable.


 In your example, you are actually faulting it because you are going outside the boundaries.

« Last Edit: September 11, 2019, 09:18:00 pm by jamie »
The only true wisdom is knowing you know nothing

Anonimista

  • New Member
  • *
  • Posts: 19
Re: Why is an enumeration out of range error not cought compile time
« Reply #2 on: September 11, 2019, 09:22:07 pm »
hm, I only get the error when ord(s) is -1. I guess my question is why are enumeration bounds not checked at compile time.

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 11382
  • FPC developer.
Re: Why is an enumeration out of range error not cought compile time
« Reply #3 on: September 11, 2019, 09:22:52 pm »
I think pred(s) and succ(s) are simply not inlined as intrinsics in this code. Then the increment/decrement doesn't happen in compiletime, so no error.

Anonimista

  • New Member
  • *
  • Posts: 19
Re: Why is an enumeration out of range error not cought compile time
« Reply #4 on: September 11, 2019, 09:43:29 pm »
Thanks! New to freepascal and not quite understand much but it is what it is.

 

TinyPortal © 2005-2018