r/learnprogramming • • 1d ago

[C++] Using macro to wrap code block between "enter/exit" functions not working if using 'return'

I've been looking through some code that uses a lot of functions to disable/restore the CPU interrupt flag to prevent interrupts at critical code segments. While just using the function calls themselves work, a neater and less error prone solution would be something that looks similar to the using statement in C#.

I was wondering if implementing something like this on C++ would be possible and this is as far as I've gotten so far, but the RestoreIRQ(f) function is not executed if leaving the code segment with a return statement. I know why it doesn't work, but not how to fix it. Is there a way to alter the macro to work correctly in this case, or is this something that is not possible with C++?

Here is some sample code with some mock functions (and variable), the macro used to implement this and code examples of what currently works and what doesn't.

/* --- MOCK VAR AND FUNCTIONS --- */
/* Actually affects on hardware level... */
bool irq_flag = false;

bool DisableIRQ() {
    bool tmp = irq_flag;
    irq_flag = true;
    return tmp;
}

void RestoreIRQ(bool f) {
    irq_flag = f;
}

/* --- MACRO --- */
#define IRQSafe(body) { bool f = DisableIRQ(); body; RestoreIRQ(f); }

/* --- This works fine --- */
IRQSafe({
    /* Some code... */
})

/* --- This doesn't work --- */
/* IRQ state is not restored... */
IRQSafe({
    /* Some code... */
    return;
})
2 Upvotes

13 comments sorted by

5

u/Aggravating_Chef_656 1d ago

Use RAII instead of a macro: put DisableIRQ() in a constructor and RestoreIRQ() in the destructor. The destructor runs whenever the scope exits, including on return or an exception.

struct IRQGuard { bool f = DisableIRQ(); ~IRQGuard() { RestoreIRQ(f); } };

{ IRQGuard g; /* code */ return; } // restored

3

u/X-Neon 1d ago edited 1d ago

The better approach is to use RAII. Create a class which disables IRQ on construction, and restores it on destruction.

class IrqGuard
{
public:
    IrqGuard() {
        disable_irq();
    }

    ~IrqGuard() {
        restore_irq();
    }

    IrqGuard(const IrqGuard&) = delete;
    IrqGuard& operator=(const IrqGuard&) = delete;
    IrqGuard(IrqGuard&&) = delete;
    IrqGuard& operator=(IrqGuard&&) = delete;
};

// Usage
void my_function()
{
    foo();

    {
        // IRQ disabled in this block
        IrqGuard irq;

        bar();
    }

    // IRQ restored
    baz()
}

Because destructors always run, no matter how you leave the scope with the guard in, the IRQ will always be restored.

1

u/captainAwesomePants 1d ago

RAII is definitely, definitely what you want.

That said, if for some reason you HAD to use a macro, and you wanted to be a little sarcastic about it, you could use RAII in your macro :)

#define IRQSafe(...) \
do { \
    IrqGuard CONCAT(_irq_guard_, __LINE__); \
    __VA_ARGS__ \
} while (false)

1

u/kitsnet 1d ago

As others say, it's a textbook case for RAII. However, without RAII, it is also a textbook case for function objects (and lambdas in particular).

In general, if you need to create your own macros in C++, you are highly likely doing something wrong (one exception could be static reflection).

1

u/StewedAngelSkins 1d ago

Other exception is anything that needs to return... man I wish C++ had something like Rust's ? operator.

1

u/kitsnet 1d ago

std::expected has monadic member functions, which enforce code with more predictable results if there are side effects.

1

u/StewedAngelSkins 1d ago

I don't know if they're categorically more predictable. They all accept closures so you can still capture anything you want and end up with side effects. Monads are a good way to handle some kinds of logic, but for something like a guard clause it ends up meaning that you have to write your entire function body in a lambda. At that point I'd personally use a macro, or at least just explicitly write out the early return.

1

u/kitsnet 1d ago

It's not about the avoidance of side effects. It's more about knowing which side effects have happened at the moment you decide to do an early return.

1

u/StewedAngelSkins 1d ago

But I don't think monads help with that. The monad's error branch is effectively an early return (in the sense that it skips everything below it). You still have to do the same reasoning to figure out which parts of the code has run.

1

u/kitsnet 1d ago

I mean, in C++, if you had multiple try propagation subexpressions inside an expression, it might be unobvious and non-deterministic which side effects have taken place. The same problem as with exceptions.

1

u/StewedAngelSkins 1d ago

that's true, doing it purely with monads does force you to at least complete the expression. i don't personally consider this to be worth the compromise, but i get what you mean. i feel like in C++'s case the problem isn't just the lack of a ? operator. really all i want is a way to represent a kind of "assign or branch" structure, like this:

let Ok(result) = fallible() else {
    return Err("it failed");
}

// result is usable here

seems like it wouldn't have the problems you mention with fallible subexpressions. i actually think something like this would be a good fit for C++.