Professional Documents
Culture Documents
Difference Between && and &: && & && & Bool - Exp1 && Bool - Exp2 Bool - Exp1 & Bool - Exp2
Difference Between && and &: && & && & Bool - Exp1 && Bool - Exp2 Bool - Exp1 & Bool - Exp2
Difference Between && and &: && & && & Bool - Exp1 && Bool - Exp2 Bool - Exp1 & Bool - Exp2
Introduction
Hello everyone, in this article we will learn a very important and basic part of the AND and OR
operators. It is not dependent on the language; its just logic and optimization. As the title of the article
suggests, its all about two and and single and or two or and single or operators. So lets start.
Difference between && and &
&& is called the AND operator and & is also called the AND operator but the basic difference between
them is in the way they are executed. The syntax for && and & the same as in the following:
Now in the case of & things are different. The compiler will execute both statements and then the result
will be ANDed. Its an inefficient way of doing things because it makes no sense to execute the other
statement if one is false because the result of AND is effective only for ANDing results evaluated to
true and its possible when both statements are true.
Example:
int x = 0;
if (5 < 4 & (7 / x) == 0)
MessageBox.Show("Won't execute!");
else
{
MessageBox.Show("&& wont execute the 7/0 so no divide by zero error.");
}
Output:
int x = 0;
if (5 > 4 || (7 / x) == 0)
MessageBox.Show("|| executed because 5>4 evaluates to true.No divide by zero error.");
else
{
MessageBox.Show("Won't execute!");
}
Output:
Thats OK but the way | behaves is the same as that of &, in other words both statements are
executed regardless of the result of one statement. Check the following example and it will be clear.
Collapse | Copy Code
int x = 0;
if (5 > 4 | (7 / x) == 0)
MessageBox.Show("|| executed because 5>4 evaluates to true.No divide by zero error.");
else
{
MessageBox.Show("Won't execute!");
}
Output:
Summary
Thanks for reading this article. This article is just for information purposes, I wont recommend anyone
to use & or | instead of && or ||. Dont forget to comment and share this article.
Edit 1
As pointed out by Klaus Luedenscheidt in comment, This article doesn't deal with the original use of
'&' and '|' . These operators are very useful in performing bitwise operations. And also you can not use
'&&' and '||' for performing bitwise operations. I guess this is the only reason for their existence.
A sort example :
--if((i=45) & (j=getBool()) ) // Here you want both statements to execute, so you used &
In my opinion this is not a good way of writing the code. We should not change our variables during any
comparison. The above code will work perfectly because of '&' but in general it is not an expected way
of comparing.
Good way of writing the above code
i=45;
j=getBool();
if(i && j)
'&' and '|' are majorly used for bit wise operations.