Home > Software engineering >  Is there a way to access variable declared in for loop outside of for loop?
Is there a way to access variable declared in for loop outside of for loop?

Time:10-09

For example, there is a char named 'character' defined in a for loop. Can I possibly use the char outside of the for loop?

Code:

#include <iostream>

int main()
{
    for(int i = 0; i < 5; i  )
    {
        char character = 'a'; // Char defined in for loop
    }

    std::cout<<character; // Can this be made valid?
    return 0;
}

CodePudding user response:

No. The scope of the variable defined inside of a loop or function is just within that loop or function.

If you want to have a variable you can set a value to in a loop but also have access to outside of the loop, you can make a global variable (or just one with a wider scope). Just define the variable outside of the scope loop and set it the value you want in the loop.

CodePudding user response:

no. because variable declared inside loop has local scope that is it can be accessed inside loop only

CodePudding user response:

Nope, you can't use it outside the loop, if the definition of the variable is inside the loop

CodePudding user response:

NO as "A variable declared within a scope can NEVER be used outside of that scope". Always keep this in mind!

CodePudding user response:

Yes, you can do this indirectly in C 11 and later, with a lambda:

#include <iostream>
#include <functional>

int main()
{
  std::function<char()> fun;

  for(int i = 0; i < 5; i  )
  {
    char character = 'a'; // Char defined in for loop
    fun = [=](){ return character; };
  }

  std::cout << fun() << std::endl;
  return 0;
}

The outside scope cannot access character, but a lambda which was captured in that scope can be called, and the body of that lambda has character in scope, and can return it for us.

In a language with real lambdas, the lambda would access the actual character variable; the original one created in that scope. In C , the = in [=] tells the lambda to capture the local variables it is referencing by making copies of them. Thus return character is not actually accessing the original character (which no longer exists, since the block terminated), but a copy which the lambda object carries.

  • Related