Ada Reference Manual (Ada 2022) — Legal Information

# 4.5.9 Declare Expressions

1/5
Declare expressions provide a way to declare local constants and object renamings in an expression context.

#### Syntax

2/5
declare_expression ::=
declare {declare_item}
begin body_expression
3/5
declare_item ::= object_declaration | object_renaming_declaration
4/5
Wherever the Syntax Rules allow an expression, a declare_expression may be used in place of the expression, so long as it is immediately surrounded by parentheses.

#### Legality Rules

5/5
A declare_item that is an object_declaration shall declare a constant of a nonlimited type.
6/5
A declare_item that is an object_renaming_declaration (see 8.5.1) shall not rename an object of a limited type if any operative constituent of the object_name is a value conversion or is newly constructed (see 4.4).
7/5
The following are not allowed within a declare_expression: a declaration containing the reserved word aliased; the attribute_designator Access or Unchecked_Access; or an anonymous access type.

#### Name Resolution Rules

8/5
If a declare_expression is expected to be of a type T, then the body_expression is expected to be of type T. Similarly, if a declare_expression is expected to be of some class of types, then the body_expression is subject to the same expectation. If a declare_expression shall resolve to be of a type T, then the body_expression shall resolve to be of type T.
9/5
The type of a declare_expression is the type of the body_expression.

#### Dynamic Semantics

10/5
For the evaluation of a declare_expression, the declare_items are elaborated in order, and then the body_expression is evaluated. The value of the declare_expression is that of the body_expression.

#### Examples

11/5
Example of use of a declare expression as a replacement postcondition for Ada.Containers.Vectors."&" (see A.18.2):
12/5
with Post =>
(declare
Result renames Vectors."&"'Result;
Length : constant Count_Type := Left.Length + Right.Length;
begin
Result.Length = Length and then
not Tampering_With_Elements_Prohibited (Result) and then
not Tampering_With_Cursors_Prohibited (Result) and then
Result.Capacity >= Length)

Ada 2005 and 2012 Editions sponsored in part by Ada-Europe