Tagging of arguments ref/out, or just out

Max Klyga max.klyga at gmail.com
Sun Aug 7 14:14:56 PDT 2011


One the main reasons c# has mandatory out and ref at call site is code 
versioning. If some function took an argument by value but was changed 
to take if by reference, without annotations compiler would treat this 
as an error, preventing a potential bug.

So this feature has to be either mandatory or not. Making it optional 
leads to confusion as Jonathan mentioned.
But it's kinda late to change the language now, with all the code outthere.

On 2011-08-07 23:42:30 +0300, bearophile said:

> This is a recently opened (not by me) enhancement request thread:
> http://d.puremagic.com/issues/show_bug.cgi?id=6442
> 
> It proposes something that I remember was discussed and refused two 
> times in past: to require (but only optionally!) "ref" and "out" at the 
> calling point, as C#4 instead always requires (optionally for COM):
> 
>     void foo(ref int bar) { ... }
>     int i = 0;
>     foo(ref i);   // <------- here
> 
>     void foo(out int bar) { ... }
>     int i = 0;
>     foo(out i);   // <------- here
> 
> 
> Jonathan M Davis has then argued that they clutter the code, and that 
> making them optional makes them kind of useless. See the thread for 
> more details.
> 
> -----------------
> 
> After thinking some about it, I have suggested a related but 
> alternative proposal: to ask only for the "out" at the calling point, 
> make it obligatory if you compile with -warning and optional otherwise 
> (for a long time "override" was like this). I think having "out" at the 
> calling point is more useful than "ref".
> 
> Currently D 2.054 gives no warnings/errors on a program like this (I 
> think the C# compiler gives something here):
> 
> 
> void foo(out int x) {
>     x = 5;
> }
> void main() {
>     int y = 10;
>     foo(y);
> }
> 
> 
> The problem here is the initialization of y to 10 always gets ignored. 
> Assigning something to y, *not using y in any way*, and then using it 
> in a "out" function argument call, is in my opinion a code smell. It's 
> wasted code at best, and sometimes it's related to possible semantic 
> bugs.
> 
> Using "out" at the calling point doesn't fix that code, but helps the 
> programmer to see that the assign of 10 to y is useless, and it's 
> better to remove it:
> 
> 
> void foo(out int x) {
>     x = 5;
> }
> void main() {
>     int y = 10;
>     foo(out y);
> }
> 
> 
> In my opinion "ref" arguments don't have the same need of being tagged 
> at the calling point because a function that uses "ref" often reads and 
> writes the argument (otherwise you use "in" or "out"), so in a ref 
> argument assigning something to y before the call is more often 
> meaningful:
> 
> 
> void foo(ref int x) {
>     x++;
> }
> int main() {
>     int y = 10;
>     return foo(y);
> }
> 
> Bye,
> bearophile




More information about the Digitalmars-d mailing list