Field assignments are reordered in record creations

orbitz@REDACTED orbitz@REDACTED
Tue May 23 21:15:17 CEST 2006


I don't believe what is happen is what you think is happening.  The  
issue is that the order of execution in a single sequence point is  
not defined.  Your code does no say anything about which record  
fields gets assigned first, simply which function gets executed  
first.  You cannot depend on the order of execution of an expression  
to reflect how you wrote it.  Compilers are generally free to execute  
expressions in whatever order is easiest for them.


On May 22, 2006, at 2:56 AM, Romain Lenglet wrote:

> I just remarked that in a record creation expression, the fields
> assignments are reordered to match the record definition. This
> is significant if the fields assignments have side effects (e.g.
> read from a file).
>
> For instance, executing:
>
> -module(test1).
> -record(rec, {foo, bar}).
> -export([start/0]).
> start() ->
>     #rec{foo = io:format("foo"), bar = io:format("bar")}.
>
> outputs:
>
> foobar{rec,ok,ok}
>
> But executing:
> ...
> -record(rec, {bar, foo}).
> ...
>     #rec{foo = io:format("foo"), bar = io:format("bar")}.
>
> outputs:
>
> barfoo{rec,ok,ok}
>
> Only the order of fields in the record definition changed, but
> the side effects are different.
>
> Just to demonstrate that the order of assigments in a record
> creation is not significant, executing:
>
> ...
> -record(rec, {foo, bar}).
> ...
>     #rec{bar = io:format("bar"), foo = io:format("foo")}.
>
> outputs:
>
> foobar{rec,ok,ok}
>
>
> The Erlang Reference Manual only says:
> "The fields may be in any order, not necessarily the same order
> as in the record definition, and fields can be omitted."
>
> Please someone also add that field assignments are reordered to
> match the order of fields in the record definition.  This is not
> obvious.
>
> -- 
> Romain LENGLET




More information about the erlang-questions mailing list