Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to go to higher level scope condition's else in C++?

Tags:

c++

algorithm

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
    }
like image 759
Zack Lee Avatar asked Aug 05 '18 13:08

Zack Lee


People also ask

Whats a scope C++?

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.

Is C++ block scoped?

The Scope Levels Here are the three levels of scope in a C++ program: global, local, and block.

What does out of scope mean in C++?

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.


2 Answers

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
like image 101
Jack Avatar answered Oct 26 '22 08:10

Jack


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();
}
like image 33
Jesper Juhl Avatar answered Oct 26 '22 08:10

Jesper Juhl