Why is named association required for a one-element record aggregate?

蓝咒 提交于 2019-12-11 07:15:30

问题


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 => <>);


来源:https://stackoverflow.com/questions/26955655/why-is-named-association-required-for-a-one-element-record-aggregate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!