r/learnprogramming • u/Flying_Turtle_09 • 1h 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;
})
1
u/Aggravating_Chef_656 1h 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
1
u/X-Neon 1h ago edited 1h ago
The better approach is to use RAII. Create a class which disables IRQ on construction, and restores it on destruction.
Because destructors always run, no matter how you leave the scope with the guard in, the IRQ will always be restored.