How to make a function that accepts optional struct but can accept struct literal too
JN
666total at wp.pl
Fri Oct 15 20:33:33 UTC 2021
Is there some nice way of achieving something like this C99 code
in D?
```c
#include <stdio.h>
typedef struct {
int x, y;
} inputs_t;
void foo(inputs_t* optional_inputs)
{
if (!optional_inputs) {
printf("0 0\n");
} else {
printf("%d %d \n", optional_inputs->x,
optional_inputs->y);
}
}
int main(void) {
foo(NULL); // prints 0 0
foo(&(inputs_t){.x = 5, .y = 6}); // prints 5 6
}
```
below code won't work. Yes, I know I can just use a local
variable in this case and pass a pointer, but I'd like to get it
to work with literal structs too.
```d
import std.stdio;
struct inputs_t {
int x, y;
};
void foo(inputs_t* optional_inputs)
{
if (!optional_inputs) {
writeln("0 0");
} else {
writeln(optional_inputs.x, optional_inputs.y);
}
}
void main() {
foo(null); // prints 0 0
foo(&(inputs_t(5, 6))); // error: inputs_t(5,6) is not an
lvalue and cannot be modified
}
```
More information about the Digitalmars-d-learn
mailing list