defined function

mind to explain this program for me?


#include <iostream>
using namespace std;

static int i = 100;
void abc()
{
static int i = 8;
cout << "first = " << i++ << endl;
}

int main()
{
static int i = 2;
abc();
cout << "second = " << i << endl;
abc();

return 0;
}
Last edited on
You have three distinct variables all with the same name.
This is generally a bad idea as you have to play silly games to figure out which one has the nearest scope in any given situation.

Hence, we have a warning to specifically identify this mis-feature.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ g++ -Wshadow foo.cpp
foo.cpp: In function ‘void abc()’:
foo.cpp:7:12: warning: declaration of ‘i’ shadows a global declaration [-Wshadow]
 static int i = 8;
            ^
foo.cpp:4:12: note: shadowed declaration is here
 static int i = 100;
            ^
foo.cpp: In function ‘int main()’:
foo.cpp:13:12: warning: declaration of ‘i’ shadows a global declaration [-Wshadow]
 static int i = 2;
            ^
foo.cpp:4:12: note: shadowed declaration is here
 static int i = 100;
            ^
^^ the program is likely a nonsense program to help you understand variable scopes and how easy it is to confuse yourself when you reuse the same variable name over and over carelessly.

later, you will run into another idea, the this-> class name reuse bad design.
in short, its similar, and you may see it a lot. I have made the class variable bold in all cases to make it easier to follow.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct classname {int i; … more things};  

//the poor version reuses the class variable name and requires extra mess to resolve:
void classname::foo( int i)  //this is a function that is part of a class/struct
{
   this->i = i; //the class one is set to the parameter version. 
}

//the better version:
void classname::foo(int local_i)
{
   i = local_i;  //does not need to be resolved which is which, they have distinct names.
}


regardless, the point of all this, and the lesson, is this:
do not reuse the same names over and over without great care. Its common to reuse local variables, esp loop counters like i,j,k and so on, but that implies that you don't want OTHER i,j,k floating around (like at the global scope).
It bears repeating as well that global variables are nothing but trouble. Do not use them outside of these kinds of examples (of things not to do to yourself and your readers).
Last edited on
Topic archived. No new replies allowed.