Reputation: 373
Can someone explain to me what this line of code means and whether it is good practice?
It seems to me that it is trying to assign one or another value to a boolean, but it is not clear.
myBoolVar = isC || isP || isX;
Upvotes: 6
Views: 485
Reputation: 19230
The ||
operator represents a conditional OR.
myBoolVar will be true if any of isC, isP, or isX is true.
It is similar to the | operator between boolean operands except that if the left-hand-side evaluates to true, the right-hand-side will not be evaluated.
As to whether it's good practise, consider a more verbose semantic equivalent:-
bool myBoolVar;
if (isC)
{
myBoolVar = true;
}
else if (isP)
{
myBoolVar = true;
}
else if (isX)
{
myBoolVar = true;
}
In particular, consider which one you would prefer to maintain. For the most part, I would expect that folks consider the terser myBoolVar = isC || isP || isX;
to be more readable.
I see from the comments below that you make an argument about programming being about simplicity and not about "showing off". I agree that programmers often try to compact or deliberately obfuscate code for their own satisfaction - often to the detriment of the project. This is probably not one of those cases. I might name the variables more clearly and I might encapsulate it behind an appropriately-named property, but I'd definitely use the a || b || c
construction over something more verbose.
If you feel you have a clearer way to express it, share it with us and we can discuss it.
Upvotes: 14
Reputation: 42390
the ||
operator simply means OR. So in pseudocode you might say
myBoolVal = isC OR isP OR isX
What this does in plain english...
"If isC is true, or isP is true, or isX is true, then myBoolVal is true, otherwise, myBoolVal is false"
Upvotes: 3
Reputation: 10644
Returns true if any of them has true
value
bool myBoolVar = false;
if( isC == true || isP == true || isX == true)
{
myBoolVar = true;
}
Upvotes: 2
Reputation: 17194
It is conditional OR:
It means Any of the variable from isC, isP, isX
is True
then myBoolVar
is True
That is:
myBoolVar = if(isC == true) || if(isP == true) || if(isX == true)
Upvotes: 1
Reputation: 33149
This is the conditional OR
. The values of isC
and isP
and isX
are OR
-ed together.
http://msdn.microsoft.com/en-us/library/6373h346.aspx
All you need to do is Read The Fine Manual.
Upvotes: 5