How to make a function that accepts optional struct but can accept struct literal too

Paul Backus snarwin at gmail.com
Fri Oct 15 21:47:21 UTC 2021


On Friday, 15 October 2021 at 20:33:33 UTC, JN wrote:
> 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
> }
> ```

```d
static global(alias value) = value;

struct Inputs { int x, y; }

void foo(Inputs* inputs)
{
     import std.stdio;
     if (inputs is null)
         writeln("0 0");
     else
         writeln(inputs.x, " ", inputs.y);
}

void main()
{
     foo(null);
     foo(&global!(Inputs(5, 6)));
}
```


More information about the Digitalmars-d-learn mailing list