Why is named association required for a one-elemen

2019-08-12 03:26发布

问题:

When an aggregate contains only one element, as below, positional notation results in a compilation error and we have to use named notation only. Why?

type singleton is record
   v : integer;
end record;

v1 : singleton := (0);

results in the compiler message

check.adb:6:23: positional aggregate cannot have one component
check.adb:6:23: write instead "V => ..."
gnatmake: “check.adb" compilation error

whereas this is OK:

v2 : singleton := (v => 0);

回答1:

Parentheses round an expression are redundant, so (0) = 0 and it's an integer not an array aggregate.

So, for the special case of a one-element aggregate, named association is required to distinguish an aggregate from a simple value.

Contrast this with (0,0) which can only be an aggregate; therefore there is no ambiguity.

Even though in the context of the question, it's obvious to a human programmer which is intended, that will not always be the case.

Consider a one-element aggregate in a multi-dimensional array which is one field of a record; there can be ambiguities that the compiler cannot resolve (at least, before reading a whole lot more of the source file!) and would make life pretty difficult for anyone reading the program.



回答2:

You don't have to use named notation.

v1 : singleton := (others => 0);

This will assign 0 to all elements in v1 and the compiler will know that is not a number but an array instead.

If the record happen to have different types you could use

v1 : singleton := (others => <>);


标签: record ada