Greetings,
Is there any gotchas to using an equation to set a flag vs using If...Then? This is a general coding question for Arduino and/or C. FYI, both of them worked in my application (but I like that one-liner in 2nd example!).
//Probably most accepted way:
if(GUL_PulseK3Len >= GUL_MINPULSEWIDTH)
{
gFlg_GotPulseK3Len = true;
}
//One-liner (allergic to white space)...is it [more] efficient :
gFlg_GotPulseK3Len = (GUL_PulseK3Len >= GUL_MINPULSEWIDTH);
The first one is easy to read. The second marginally less so, though by no means difficult.
If it’s in your own code, that no one else will see, use your favorite. If you’re showing it to others or seeking help, I’d prefer the clearer version.
certainly not, because there is a difference in the logic. The first version changes the flag only when the condition ist true . If not the flag is left unchanged ( if it is true already, it will stay true even if the comparison is false )
The second version in any case sets the flag according to the result of the comparison.
The two versions would only be identical if there is an else block in the first version, that resets the flag to false or you set the flag definitely to false before the if.
Thanks for your response. That is a good point...that on its own it can set true or false whereas the If...Then can only set to true (so either needs a 'else' statement or would have to have been the 'fail' value, e.g. gFlg_GotPulseK2Len = false in loop(), prior to being evaluated in a ISR or some other function.
Alternatively another one-liner is the ternary but I HATE the way it looks in C -- I actually wrote a macro to make it look like VB's IIF().
I'd prefer the second version too. In my opinion its clear as has no side effects. ( OK, may be a little bit hard to understand for beginners .... )
I would not use the ternary operator to only set a flag to true or false.
its mostly personal style. The compiler will not care (if the code would have been equal).
But your example in #1 shows, how one gets confused by code.
imho a if / else is clear without any guessing.
My last choice would be a precompiler #define just to bring in another variant what's covered already in the language.
The first way is more maintainable. If you needed to more than just set the flag, you only need to add lines to the controlled block. The second way, you would have to re-structure everything.
Not if there is intervening code that references it, because of the complexity of tracking its state. Then "it depends"... may or may not undergo optimization.
Key issue would be whether the boolean variable's value could be changed by the code in the conditional blocks that it's used in.