This code I found while doing code review. Is there any hidden problem in this code or is it just fine?
myBool = myBoolA || ( oldState == AS_PLAYING ); //code #1
Edit: One typing mistake ( myBoolA
in place of myBool
) by me created some nasty confusion; I am really sorry for that.
Actually the code to be reviewed is :
myBool = myBool || ( oldState == AS_PLAYING ); //code #1, not myBoolA
and my suggested code is:
if( oldState == AS_PLAYING ) myBool = true; //code #2
Advantages with code#2 IMO :
myBool
is unintialized to begin with, there won't be Undefined behaviour. myBool = myBoolA || ( oldState == AS_PLAYING );
is absolutely fine.
||
is a sequencing point in C++, so even if the expression on the right hand side depends on the left hand side (perhaps oldState
is a reference to myBool
or myBoolA
), the behaviour will be defined.
Your recommendation in changing this to
if( oldState == AS_PLAYING ) myBool = true;
is actually functionally different (the assignment to myBool
is different for example), so don't change it to that.
Finally, note that the short-circuiting nature of ||
is obviated if ||
is overloaded. So always check that when refactoring code.
As per your comments later,
You can refactor as follows:
if(!myBool)
myBool = (oldState == AS_PLAYING);
this will save one extra assignment operation. when myBool
is true before if
myBool = myBoolA || ( oldState == AS_PLAYING );
//code #1 seems to be correct version.
Your version is not equivalent to this. How? See
if myBoolA
is true and ( oldState == AS_PLAYING )
is false. myBool
will still be true, but in your version, it will not be set.
After EDIT
if( oldState != AS_PLAYING ) myBool = false; //code #2 more readable IMO
This will be fine only if, myBool
is initialized with true
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.