I can not understand this programming style

Can someone explain to me what this line of code means and is this good practice?

It seems to me that he is trying to assign one or another value to a logical one, but this is not clear.

myBoolVar = isC || isP || isX; 
+6
source share
5 answers

Operator || represents a conditional OR.

myBoolVar will be true if any of isC, isP or isX is true.

He looks like | operator between boolean operands, except that if the left side evaluates to true, the right side will not be evaluated.

As for good practice, consider a more detailed 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 keep. For the most part, I would expect people to consider terser myBoolVar = isC || isP || isX; myBoolVar = isC || isP || isX; more readable.

From the comments below, you can see that you are making the argument that programming is about simplicity, not "demonstration." I agree that programmers often try to compromise or deliberately confuse code for their own satisfaction - often to the detriment of the project. This is probably one of these cases not . I can call the variables clearer, and I could encapsulate it behind an appropriately named property, but I would definitely use the construction a || b || c a || b || c a || b || c over something more verbose.

If you feel that you have a clearer way to express this, share it with us and we can discuss it.

+14
source

This is a 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 have to do is read the Great Guide.

+5
source

operator || just means OR. So in pseudo code you can say

 myBoolVal = isC OR isP OR isX 

What does it do in plain English ...

"If isC is true or isP is true or isX is true, then myBoolVal is true, otherwise myBoolVal is false"

+3
source

Returns true if any of them has true

 bool myBoolVar = false; if( isC == true || isP == true || isX == true) { myBoolVar = true; } 
+2
source

conditional OR :

This means that Any variable from isC, isP, isX is True , then myBoolVar is True

I.e:

 myBoolVar = if(isC == true) || if(isP == true) || if(isX == true) 
+1
source

All Articles