Overview of Ada 2022
Jeff Cousins
Contents   Index   Search   Previous   Next 

7.13 Getting the representation of an enumeration value

It has long been possible, with Ada, to define non-default numeric values for an enumeration type, using a representation clause, as in:
type Status is (Off, Ready, On);
for Status use (Off => 1, Ready => 2, On => 4);
for interfacing to hardware where one, and only one, of a group of three bits should be set. It was not possible to subsequently query what numeric value represented a given enumeration literal, or vice versa, though. This may have been to discourage users from adopting a C mentality of thinking in terms of the numeric values. But to save the user from workarounds, typically involving Unchecked_Conversion, Ada 2022 (via Getting the representation of an enumeration value AI12-0237) provides attribute 'Enum_Rep to return the number representing a given enumeration literal, and 'Enum_Val to return the enumeration literal represented by a given number (see RM 13.4). Thus:
   My_Status     : Status := ...;
   Rep     : Integer;
begin
   Rep     := Status'Enum_Rep (My_Status);
   My_Status     := Status'Enum_Val (Rep);

Contents   Index   Search   Previous   Next 
© 2021, 2022 Jeff Cousins