I have the exact same lines of code in the both do something
section so I want to merge the two sections into one.
But I don't want to create a separate function for do something
.
Is there a way to go to condition A
's else when it reaches condition B
's else?
if (conditionA)
{
//some code here
if (conditionB)
{
}
else
{
//do something
}
}
else
{
//do something
}
When you declare a program element such as a class, function, or variable, its name can only be "seen" and used in certain parts of your program. The context in which a name is visible is called its scope. For example, if you declare a variable x within a function, x is only visible within that function body.
The Scope Levels Here are the three levels of scope in a C++ program: global, local, and block.
In C++ a scope is a static region of program text, and so something "out of scope", taken literally, means physically outside of a region of text. For instance, { int x; } int y; : the declaration of y is out of the scope in which x is visible.
Jumping through code is definitely discouraged, if you really want to minimize the code then the only thing you can do is to rearrange the flow to better suit your needs, eg:
if (conditionA)
{
some code
if (conditionB)
do something else
}
if (!conditionA || !conditionB)
do something
If you (as indicated in the comments) don't want to create a function that you need to pass 6 arguments, then you could use a lambda like this:
const auto do_something = [&] { /* do stuff with captured reference variables */ };
if (conditionA) {
// some code here
if (conditionB) {
// stuff
} else {
do_something();
}
} else {
do_something();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With