Im wondering if it is possible to have a variable changed after returning its value?
The function in question is a simple get function for a private Boolean flag variable. I would like reads of this flag to be destructive, so I thought:
bool myGet (context_t * someContext) {
return (someContext->flag) ? (someContext->flag = false) : false;
}
Reasoning that the result of evaluating the statement (someContext->flag = false)would be true, but it appears not.
Maybe it's evaluated before the condition (someContext->flag)?.
Is there any other way to achieve the intended functionality without resorting to temporarily storing the flag value, clearing the flag and then returning the temporary copy? Thanks.
All of the argument to return must be evaluated before the return itself is evaluated, i.e. before execution leaves the current function.
The value of an assignment is the assigned value, so it's false as you experienced.
I think the closest you can come is with post-increment, but that will of course strictly limit the values available.
There's nothing wrong with doing it the explicit way:
bool getAndClear(context_t *someContext)
{
if(someContext->flag)
{
someContext->flag = false;
return true;
}
return false;
}
it's very clear and way easier to understand than your scary code. It's easy to imagine that it's possible for compiler to optimize it, since it's pretty straight-forward.
If I wanted to get clever, I'd probably use something like:
bool getAndClear2(context_t *someContext)
{
const bool flag = someContext->flag;
someContext->flag ^= flag; /* Clears if set, leaves alone if not set. */
return flag;
}
Note that it doesn't branch, which is sometimes nifty. But, again, being clever is not always the most awesome path to take.
Also note that I consider it a requirement that this function isn't just named "get" something, since it doesn't take a const pointer that would be an instant warning flag in my head. Since it has super-strange (for a getter) side-effects, that should be reflected in the name somehow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With