AND and OR operators?

bigmike2238

Member
Joined
Dec 24, 2013
Messages
7
Programming Experience
Beginner
If you have time, or come back to this thread, do you have any information on the AND and OR operators? I've had a lot of trouble with this, and wrapping my head around the correct way to use them has been...an exercise in frustration. I'm asking here because I don't want to start a new thread for such a small question. :)

-Mike
 

JuggaloBrotha

Staff member
Joined
Apr 23, 2011
Messages
176
Location
Lansing, MI; USA
Programming Experience
10+
What exactly is your issues with them?
Personally I only use the And (&) and the Or (|) operators when doing bit-shift type calculations, for everything else I use the short circuited AndAlso (&&) and the short circuited OrElse (||) as those are more efficient logic handling.
 

bigmike2238

Member
Joined
Dec 24, 2013
Messages
7
Programming Experience
Beginner
Hi JB,

I guess my problem was understanding exactly what they do. Until I read your post, I thought (Or) was represented by || not |, and (And) was represented by && not &. My frustration is pretty much self-explanatory. I will have to look into what bit-shift calculations are, as this is the first time that I am seeing the term. I pretty much use these for if-then statements that require more than one condition. Thank you for posting back.

- Mike
 

JuggaloBrotha

Staff member
Joined
Apr 23, 2011
Messages
176
Location
Lansing, MI; USA
Programming Experience
10+
So you just need an explanation of what these do?

Let's take a look at the singular And (&) and the singular Or (|):
When you need to have logic that checks for multiple conditions and you need to have both (or all) evaluated you would use the & or | for this.
As in:
int x = 1;
int y = 3;
if (x == 0 & y == 3)
Since we used the singular & for this even though it's failed on the first condition (because x is equal to 1) the 2nd condition is still evaluated (it checks to see if y is equal to 3).
We can shortcut this logic by using the short circuited And which is &&:
int x = 1;
int y = 3;
if (x == 0 && y == 3)
Since the first condition still fails the code in this case wont even look at the y equals 3 because that check wont effect the outcome, it's already known to equate to a false overall.
Same thing for the Or/OrElse.
Here's an article explaining this a little more: & vs && and | vs || - MSHN Social
MSDN Social said:
& is a bitwise AND operation
| is a bitwise OR operation
&& is a logical AND
|| is a logical OR
Here's more explanation on bitwise operations: Bitwise Operation - Wikipedia
 

bigmike2238

Member
Joined
Dec 24, 2013
Messages
7
Programming Experience
Beginner
Hi JB,

Yes! This is what I was looking for. Thank you for explaining the difference between bitwise and logical operators. I will defiantly give these posts a read.

- Mike
 
Top Bottom