You use a nested if when the condition is dependent upon another condition. For example:
if (ptr != nullptr)
{
// ptr is non-null -- test the value it refers to
if (ptr* == 0)
{
// the value pointed to by ptr is zero
}
else
{
// the value pointed to by ptr is non-zero
}
}
In this case, the alternative to a nested if creates an inefficiency:
if (ptr != nullptr && *ptr == 0 )
{
// ptr is valid and refers to the value zero
}
else if (ptr != nullptr)
{
// ptr is valid and refers to a non-zero value
}
In this example, the expression "ptr != nullptr" is evaluated twice when ptr is valid and refers to a non-zero value. The nested if only evaluates this expression one time.
Copyright © 2026 eLLeNow.com All Rights Reserved.