0

How to get the following code to work?

int main(){
    bool flag = true;

    if(flag){
        // note that I donot want to define variable globally.
        int a = 5;
    }

    if(flag){
        // but I still want to use this local variable within the same condition.
        a++;
    }
}

Note that I don't want to define this variable globally or use a static variable. I'm curious if there is a way for c++ to make local variables available in all regions with the same conditions?

  • 4
    No, that's the whole point of being local / scoped. – wohlstad Feb 15 '23 at 13:38
  • 2
    Change the variable's scope to be the scope you want. – JohnFilleau Feb 15 '23 at 13:39
  • Make a function flag() that returns the correct value? – Pepijn Kramer Feb 15 '23 at 13:48
  • If I understand correctly, you want a variable that's accessible in two different functions but that is not global. Have you considered making a class including both functions and a private variable accessible to both functions? (Of course in C++, "functions" in a class are normally referred to as "methods".) – David Yockey Feb 15 '23 at 14:03
  • Is [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional) what you're looking for? – Solomon Ucko Feb 15 '23 at 14:10
  • 1
    @DavidYockey • in C++, functions in a class are normally referred to as **member functions**. In other OO languages, and in OOP in general, they are referred to as **methods**. (But I'm with you, and I call them *methods* as well.) – Eljay Feb 15 '23 at 14:12
  • 1
    @Eljay Ah, that's true. Guess I'm too used to thinking in OOP terms. – David Yockey Feb 15 '23 at 14:16
  • If you want to use a local variable in a different scope (such as a different function) pass a reference to it to the function – Kevin Feb 15 '23 at 14:21
  • 1
    Define `int a{};` locally in **main**, rather than locally within a nested scope within **main**. – Eljay Feb 15 '23 at 16:23
  • Related/dupe: [Using local variable outside its scope](https://stackoverflow.com/questions/50712236/) – Remy Lebeau Feb 15 '23 at 20:26

4 Answers4

3

What you ask for literally is a local variable that is not a local variable. Thats not possible.

On the other hand, you basically want data + code, thats a class. If you wrap it in a class your function can look like this:

int main(){   
    Foo f;
    f.doSomething();
}

And the class can be this

struct Foo {
   bool flag = false;
   int a = 0;
   void doSomething() {
      if (flag) ++a;
   }
};
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

What you're directly asking for isn't possible. You'll have to declare something up front. If it's about avoiding construction of objects until you have some relevant detail, you could use std::optional

int main()
{
    std::optional<int> a;

    if(flag)
    {
       a = 10;
    }

    if(a)
    {
        *a++;
    }
}
Chad
  • 18,706
  • 4
  • 46
  • 63
1

You set the variable's scope to be the scope you want it to be.

int main(){
    bool flag = true;

    // declare it in this scope if you want it to persist
    // thru this scope
    int a;

    if(flag){
        a = 5;
    }

    if(flag){
        a++;
    }
}
JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
  • Thanks. Maybe I did not make it clear, what I want is to define in local, instead of define in global, and I still want to use the local variable in another place. – jingrui yu Feb 15 '23 at 13:43
  • @jingruiyu `a` is defined directly within the function without any storage specifiers, so it's a local variable. – Solomon Ucko Feb 15 '23 at 13:46
  • 1
    @jingruiyu a variable local to a scope is, well, local to the scope where it is declared, period. What you're asking for for doesn't make much sense. What is your use case? Why is the method suggested in the answer a problem? – Jabberwocky Feb 15 '23 at 13:55
  • 1
    Can you say more about _why_ you want to do it the way you write in your original question, and why my answer doesn't get you what you want? This feels like an XY problem. What do you think you gain by not declaring the variable in the wider scope? – JohnFilleau Feb 15 '23 at 15:00
1

No.

According to section 6.4.3, basic.scope.block:

1 Each

  • (1.1) selection or iteration statement ([stmt.select], [stmt.iter]),
  • [...]
  • (1.4) compound statement ([stmt.block]) that is not the compound-statement of a handler

introduces a block scope that includes that statement or handler.

A variable that belongs to a block scope is a block variable.

According to section 6.7.5.4, basic.stc.auto, clause 1:

Variables that belong to a block or parameter scope and are not explicitly declared static, thread_­local, or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45