Jump to content

Ada Programming/Attributes/'Pos

From Wikibooks, open books for an open world

Ada. Time-tested, safe and secure.
Ada. Time-tested, safe and secure.

Description

[edit | edit source]

The 'Pos attribute is defined for all discrete types. It is a function returning the argument's position number as a universal_integer; the prefix S must be a subtype name. (Universal integers are implicitly converted to any specific integer type as required by the context.)

function S'Pos (Arg: S'Base) return universal_integer;

For enumeration types, position numbers start at 0; if the argument does not denote a valid value (perhaps because of an uninitialized variable), the exception Program_Error is raised. For integer types, the attribute returns the value converted to universal_integer. Note that it is not necessary for the actual argument to belong to the subtype S.

Note that representation clauses do not affect position numbering. Whatever underlying value the enumerated value has, the position number will remain the same.

Example

[edit | edit source]
I: Integer := -30;

pragma Assert (Integer'Pos(I) = -30);  -- of type universal_integer

type My_Enum is  (Enum1, Enum2, Enum3);
for  My_Enum use (Enum1 => 2, Enum2 => 4, Enum3 => 6);
...
pragma Assert (My_Enum'Pos(Enum1) = 2);  -- Wrong, 2 is the internal representation, not the position
pragma Assert (My_Enum'Pos(Enum1) = 0);  -- Right
pragma Assert (My_Enum'Pos(Enum3) = 2);

subtype My_Enum_Sub is My_Enum range Enum1 .. Enum2;

pragma Assert (My_Enum_Sub'Pos (Enum3) = 2);  -- Enum3 does not belong to My_Enum_Sub

Another example without representation clause:

  type Color is  (Red, Blue, White);
  Object : Color := White;
begin 
  Put (Color'Pos (Object)); -- prints 2, position of White.
...

See also

[edit | edit source]

The inverse of the 'Pos attribute is 'Val.

The underlying representation can be obtained using an Unchecked_Conversion, or with the implementation-defined attribute 'Enum_Rep (GNAT).

For a detailed explanation of universal_integer, see Type System: Elaborated Discussion of Types for Signed Integer Types.

Wikibook

[edit | edit source]

Ada Reference Manual

[edit | edit source]