[comp.lang.pascal] Summary of answers to enumerated type --> string conversion

baldwin@usna.MIL (J.D. Baldwin) (12/05/89)

Last week, I asked whether it was possible to convert enumerated ordinal
types to string values.  I said I'd summarize to the net, so here it is:

6600john%ucsbuxa@hub.ucsb.edu (John Bernstein) suggested a case statement
of the form 

        case ord(<variable>) of
	    0: <return first member of set>
	    1: <return second member of set>
	    ... etc.


(real name unknown) auc.dk!cac@uunet.uucp and Shiladitya Raj Chaudhury
<raj@pic.ucla.edu> both suggested an array of strings indexed by the
enumerated type (the actual example is Chaudhury's):

	type 
	   veggies =(carrots,potatoes,tomatoes,peas....);
	   veggiearray = array [veggies] of string[20];
	
	then initialize the array as follows:
	
	var 
	   veggienames : veggiearray;
	
	begin
	    veggienames[carrots] := 'carrots';
	    veggienames[potatoes] := 'potatoes';
	       .
	       .
	and then
	
	  writeln(veggienames[carrots]);



These are nifty tricks, but we had pretty much thought of them (and variations
on them) before asking.  We wanted a direct, general conversion.

Kenneth Herron <kherron@ms.uky.edu> dashed our hopes for that by pointing out:

	The strings "red", "green", and "blue" (or whatever your values
	are named) are NOT stored in the executable, therefore there
	is no way to do I/O with the enumerated names.

Thanks, Ken.  I'll bet you like telling kids there's no Santa, too. :-)

I have confirmed this solution by compiling two equivalent programs
--one with an enumerated type, and one with a subrange of integers, and
comparing them.  In the degenerate case, the executable code is
identical.

He went on to suggest the same method as cac and raj, above (initialize an
array indexed by the defined ordinal type)--except that he declared the
array as a constant:

	type
	    colors = (red, green, blue);
	const
	    colornames:array[colors] of string[5] = ('red', 'green', 'blue');

	(Note that declaring constants like this is a turbo pascal extension)


I would add that declaring constants like this in Turbo is a glorified means
of initializing a declared *variable*--that is, there is no compiler protection
against making assignments like

	colornames[red] := 'white'

in the executable statements part.

Thanks for responding, all!
--
From the catapult of:               |+| "If anyone disagrees with anything I
   _, J. D. Baldwin, Comp Sci Dept  |+| say, I am quite prepared not only to
 __||____:::)=}-  U.S. Naval Academy|+| retract it, but also to deny under
 \      / baldwin@cad.usna.navy.mil |+| oath that I ever said it." --T. Lehrer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~