Some thoughts about C and D, return data through parameters

cosinus dummy at dummy.dummy
Tue Dec 19 01:01:57 UTC 2017


Recently I've asked my self why `C` isn't capable of returning 
multiple values at once. And I thought that the return-statement 
was primarally used only for error-handling and all the valuable 
data has been returned through the parameter-list.
If this was true then all `C`-like languages had abused the 
return-statement till  now.

This is the way most programmers are doing it:

```C
int add(int a, int b);
// ...
int c = add(a, b);
```

This is the way I think `C` was designed to:

```C
int add(int *c, int a, int b);
// ...
int c;
if(add(&c, a, b)) {
     printf("error!");
}
```

This isn't good example but think about how you are doing it with 
huge structs or even arrays.

I think the main reason why most people are using the first 
example is because it looks more like a function in math or you 
need less code to call the function or we think the 
parameter-list is for inputs only.
But the second one is faster especially with huge junks of data. 
I think a lot of unnecessary allocations has been done just to be 
able to call the function like the first example. Think about 
`std::string` in c++.

So my question is would it be a good idea to have some kind of 
implicit declarations of variables that are used as parameters:

```D
int add(decl ref int c, int a, int b);

// ...

// c is unknown here

if(add(c, 123, 456)) {
     writeln("error!");
}
// c is implicit declared at the function-call above.
assert(c == 579);
```

The good things out of this are:

* The function becomes easier to be called
* The variable `c` does not need to be default-initialized to 
keep it save
* It's like the `auto`-declaration we can already use to declare 
a variable that keeps the return-value
* It solves the problem with multiple return-values.

A second thought that came up was:
Shouldn't there be a compiler-error if someone is ignoring the 
return-value of a function?

I saw this C-code:

```C
(void)printf("Hello World!");
```

It cast's the return-value to void to tell the compiler and other 
programmer's that the return-value can be ignored.


More information about the Digitalmars-d mailing list