This is the mail archive of the egcs@egcs.cygnus.com mailing list for the EGCS project. See the EGCS home page for more information.
> Using egcs 1.1.1 stock, the following code produces unexpected output:
It is not a legal program, so the behavior is not defined. You are
initializing a non-const reference with an expression that is not an
lvalue.
The ARM (the old "standard") specified the behavior you are seeing:
create a temporary containing the expression's value and pass a reference
to that.
> #include <stdio.h>
>
> func(int &val)
> {
> val = 3;
> }
>
> main()
> {
> int val = 0;
>
> func((int)val);
> printf("Val is %d\n", val);
> }
>
> ---
> The output is 0, where I would expect it to be 3, and under other compilers
> (VC++) it is 3.
Did you get 3 on more than one compiler? Probably VC++ is optimizing
(int)val to just val at an early point in parsing, which is why the
program is "working".
> The warning during compile is:
> t3.cc: In function `int main()':
> t3.cc:13: warning: initialization of non-const reference `int &' from rvalue `int'
> t3.cc:5: warning: in passing argument 1 of `func(int &)'
>
> Why is it creating a temporary variable in the cast of int?
Because you are passing a non-lvalue to a non-const reference. Some
compilers will just give you a hard error. HP's aCC calls it a
"future error" and says
Error (future) 438: "ref.cxx", line 12 # The initializer for a non-constant reference must be an lvalue. Try changing 'int &' to 'const int &' at ["ref.cxx", line 3].
func((int)val);
^^^^^^^^^^^^^^
It, like egcs, then implements the ARM behavior of making a temporary.