• Welcome to PlanetSquires Forums.
 

Enum behavior

Started by philbar, August 18, 2020, 08:52:09 PM

Previous topic - Next topic

philbar

Talking about Enums in the last thread made me fool around with them for a minute.

Should I be surprised that this doesn't cause an error or at least a warning?


enum mything
   thinga
   thingb
   thingc
end enum

dim as mything x

x = 17
print x

sleep


Or does everybody expect that "mything" is just an ordinary integer with a few names attached to it?

Johan Klassen

that is strange, I added #print typeof(x) and the preprocessor prints MYTHING, I expected it to give me the numeric type

philbar

Yes, it just seems to me that if I declare something to be a "mything", then I ought to be able to trust it to be 0, 1, or 2. Otherwise, why declare it? The discussion of ENUM in the documentation has an example kind of like this, but it doesn't consider the possibility that the trust is broken:


enum mything
   thinga
   thingb
   thingc
end enum

sub q(byref z as mything)
   select case z
      case thinga
         print "Thinga"
      case thingb
         print "Thingb"
      case thingc
         print "Thingc"
      case else
         print "What the heck is "; z
   end select
end sub

dim as mything x
dim as single p=1.8

x = 17

q(1)
q(x)
q(9)
q(3.7)   'This gets an "implicit conversion" warning
'q(p)    'This would get a warning and an error

sleep



Are other languages that use enumerations (C, for example) that casual about what you assign to them?

Johan Klassen

C behaves just like FB in this case but FreePascal won't tolerate assigning values other than what's in the enum

#include<stdio.h>
 
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
 
int main()
{
    enum week day;
    day = 17;
    printf("%d",day);
    return 0;
}

FreePascal

program months;

type
TMonthType = (January=1, February, March, April,May, June, July, August, September, October, November, December);

var Month : TMonthType;
begin
Month:=February;
writeln(Month);
end.

philbar

Interesting.

Not surprising that Pascal would be the one to complain. It was invented as a teaching language, and I expect it to be unforgiving about coloring outside the lines.

As of 2003, Fortran has an enum statement, but it's just a way of of naming integer constants. You can't give the enum a name, and you can't define a variable to be the enum, so the question doesn't arise.