If I have this code:
if (isFoo() && isBar())
{
...
}
The program will calculate the first condition, then calculate the second condition, then determine whether to go through or skip the block below.
However, if I nest the conditions like so:
if (isFoo())
if(isBar())
{
...
}
Now it checks the first condition, and if it's false it doesn't bother with the second condition.
If the second condition (being a function) is a time-consuming memory-expensive hog it seems to be better to nest it.
Is this true? I've never seen code like this before and I made an assumption after the first example, but IMO it's highly possible.
In C#/C++ and many other languages you have two logical AND
operators actually: &
and &&
:
&
operator will evaluate both conditions
&&
operator will evaluate only first, and if it equals FALSE
, than it skips second part of expression.
The same applies for logical OR
operators too. There are two operator: |
and ||
:
|
operator will evaluate both conditions
||
operator will evaluate only first, and if it equals TRUE
, than it skips second part of expression.
So, answering your question, in your example you are using &&
, which will behave as two nested if
's
[EDIT]: Ok, it is not that easy to find example of using of | and &, personally I have used them in shortest-code contests)) This is where they are really useful (not because they are shorter than && and ||). Also consider following example:
static bool LaunchFirstRocket()
{
// Launching rocket if all is ok return true, or return false if we failed to launch it.
}
static bool LaunchSecondRocket()
{
// Launching rocket if all is ok return true, or return false if we failed to launch it.
}
static void Main(string[] args)
{
if (LaunchFirstRocket() & LaunchSecondRocket())
{
Console.WriteLine("Both rockets have launched successfully!");
}
}
Here we will force to execute both methods regardless of outcome of first one. If first rocket failed, we still want to launch second one, this is our logic. Yes, there are a LOT of other ways to write such code, but this is just an example for educational purposes.