Local/static variable scope in C++
Asked Answered
B

7

7

If I write something like this:

#include <iostream>

int main()
{
    using namespace std;

    {int n;n=5;} cout<<n;
    system("pause");
    return 0;
}

The compiler tells me that n is undeclared. Then I tried making it static, but again, the compiler tells me that it is undeclared. Doesn't a variable declated static have program scope? If not, how do I use n in this program?

Bertabertasi answered 1/3, 2013 at 7:13 Comment(6)
Maybe because of the {int n;n=5;}? Why do you need the braces there?Michaelamichaele
You're mixing visibility/accessibility and lifetime. (Please pick one of C or C++ when asking about this sort of detail. There can be subtle (or not so subtle) differences between them.)Undersize
@Michaelamichaele I want to find out if there is a way to use n with the braces there.Bertabertasi
@Undersize are there any regarding my question?Bertabertasi
In this very specific case with n non-static I don't believe so. With n static probably not in that scope. At global scope there can be. If you're going to ask a question about both languages (which you shouldn't unless your talking about interop or differences between them), at least provide a code sample that is "credible" in both languages.Undersize
@Michaelamichaele {code} creates a new scope. It isn't needed, but that is his question. Why when he creates a new scope, something doesn't work.Grist
E
22

You're confusing scope with lifetime. Static variables have a lifetime equal to the program's lifetime, but they still follow scoping rules based on where they are declared.

Encyclical answered 1/3, 2013 at 7:16 Comment(8)
So scope means where I can actually use the variable?Bertabertasi
@GeorgeIrimiciuc yes, static variable within the block is accessible only within the block, but has its lifetime tied to that of the program.Iconic
So if a variable has program lifetime, why can't I use it later? Or how can I use it outside a block?Bertabertasi
@GeorgeIrimiciuc: Change its scope by taking its declaration out of the braces.Encyclical
Yeah I just thought that static would let me use it outside the braces and couldn't find out why it actually didn't. Indeed lifetime and scope are different.Bertabertasi
@GeorgeIrimiciuc: Well, it doesn't, that's not its purpose, so I don't know what to tell you.Encyclical
If there is a way to use a variable outside the brackets it is declared in.Bertabertasi
@GeorgeIrimiciuc: If the braces delimit a namespace (like std), yeah. Otherwise, no.Encyclical
H
7

The scope of n is just between the brackets:

{int n;n=5;}

so outside of the block, you have no n variable.

Making it static just makes it's value retain even after you exit the block so that the next time you enter that block again, you can retrieve it's value from the last time you executed that block, but still it's scope is still within the brackets.

Hutchins answered 1/3, 2013 at 7:24 Comment(1)
Oh, so that memory location will never get overwritten?Grist
M
1

A variable declared static in the global scope has its scope limited to the translation unit. A variable declared static within a function has its lifetime set to be the same as the program's, but in this case does not affect its scope. You will have to put cout in the same scope as n was declared in order to use it.

Mweru answered 1/3, 2013 at 7:18 Comment(1)
Yes, but I was finding a way to use a variable outside of the brackets in which it is declared.Bertabertasi
D
1

Here the compiler gives error n is undeclared because here "{int n;n=5;}" it is declared in the braces. And braces tells us about the scope of the variable. When ever the scope ends the variable is deleted from the memory.

And for Static and local.

Static : The variable is same like global variable but its value remains constant throughout the application. And the static variable cannot be used on the other page using extern.

Local : The local variables are stored in the stack and they are deleted when they get out of scope.

Deltoid answered 1/3, 2013 at 11:56 Comment(1)
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function. static could be modified so its value remains constant could be misunderstood if the person comes from java world to C++Picture
B
0

how do I use n in this program?

using namespace std;
int main()
{
     int n;      // declare n as int
     n=5;        // assign it a value
     cout << n;  // display it.
     system("pause");
     return 0;
}
Bought answered 1/3, 2013 at 7:17 Comment(3)
Doesn't really answer the other question. And I discourage the use of system(). pause is also not a utility found on all platforms (Win only?).Mweru
Yes, but I was finding a way to use a variable outside of the brackets in which it is declared. I put systempause just to test programs :)Bertabertasi
As @VictorZamanian , it doesn't answer the question. He asked "Doesn't a variable declated static have program scope? If not, how do I use n in this program?" . He asked about the static keywordGrist
C
0

Please don't be confuse between scope and life time of a static variable. Scope means where can you access the variable. Life time of variable is duration for which variable stay in memory. In your case, Scope of x varible is within the curly braces. Life time of x would be program scope.

Compliancy answered 11/7, 2020 at 5:46 Comment(0)
M
0

Consider below example for global static scope in terms of accessibility

#include <iostream>
using namespace std;

static int y;
class A {
    public:
        void increment() {
            ++y;
        }
};

class B {
    public:
        void increment() {
            ++y;
        }
};
        
int main()
{
    A a;
    a.increment();
    cout << y << endl;
    A b;
    b.increment();
    cout << y << endl;
    B c;
    c.increment();
    cout << y;
    return 0;
}

Output

1 2 3

Here global static variable access is within both class A and B.

Consider below example for class static scope in terms of accessibility

#include <iostream>
using namespace std;

class A {
    public:
        static int y;
        void increment() {
            ++y;
        }
};

class B {
    public:
        static int x;
        void increment() {
            ++x;
        }
};

int A::y = 1;
int B::x = 1;
        
int main()
{
    A a;
    a.increment();
    cout << a.y << endl;
    A b;
    b.increment();
    cout << b.y << endl;
    B c;
    c.increment();
    cout << c.x;
    return 0;
}

output

2 3 2

Here static variable y scope is with class A and x scope is with class B. If you will try to access static variable y with class B object then it will return error. (B b -> b.y)

Life time of both static variable x and y remains till the main ends.

Maharajah answered 9/9, 2023 at 7:56 Comment(1)
static isn't a part of the scope. Those are global scope and class scope, I believe.Prevail

© 2022 - 2025 — McMap. All rights reserved.