C++ Logo

std-proposals

Advanced search

Re: [std-proposals] long return lambda

From: Fabio Alemagna <falemagn_at_[hidden]>
Date: Tue, 11 Apr 2023 15:22:48 +0200
Il giorno mar 11 apr 2023 alle ore 15:17 Frederick Virchanza Gotham
via Std-Proposals <std-proposals_at_[hidden]> ha scritto:
>
> Today I wrote the following function for a microcontroller:
>
> bool Serial(char *const p)
> {
> # define BAIL { strcpy(p, "0000000000000000"); return false; }
>
> int32_t p32[2u];
>
> if ( (SUCCESS != fpgaReadInt32(0x00f2, &p32[0])) || (0 ==
> (p32[0] & 1)) ) BAIL
>
> if ( SUCCESS != fpgaReadInt32(0x00f6, &p32[0]) ) BAIL
>
> if ( SUCCESS != fpgaReadInt32(0x00fa, &p32[1]) ) BAIL
>
> sprintf(p + 0u, "%08lx", static_cast<long unsigned>(p32[0]));
> sprintf(p + 16u, "%08lx", static_cast<long unsigned>(p32[1]));
>
> return true;
>
> # undef BAIL
> }
>
> I would have liked to use a lambda instead of a macro there, but then
> I would have to write:
>
> bool Serial(char *const p)
> {
> auto BAIL = [p](void)->void { strcpy(p, "0000000000000000"); };
>
> int32_t p32[2u];
>
> if ( (SUCCESS != fpgaReadInt32(0x00f2, &p32[0])) || (0 ==
> (p32[0] & 1)) ) { BAIL(); return false; }

Or you could just have BAIL() return false, hence the following:

bool Serial(char *const p)
{
    auto BAIL = [p] { strcpy(p, "0000000000000000"); return false; };

    int32_t p32[2u];

    if ( (SUCCESS != fpgaReadInt32(0x00f2, &p32[0])) || (0 ==> (p32[0] & 1)) )
        return BAIL();

    /* ... */
}

Received on 2023-04-11 13:23:01