static variables

Jun 1, 2013 at 7:18pm
void func1(int i){
static int staticInt = i;
cout << staticInt << endl;
}
int main(){
func1(1);
func1(2);
}
the output is 1
1
but
class Student{

public:
static int noOfStudents;
Student();
~Student();

};
int Student::noOfStudents = 0;
Student::Student(){
noOfStudents++;
}
Student::~Student(){
noOfStudents--;
}

int Student::noOfStudents = 0;
int main(){
cout <<Student::noOfStudents <<endl;
Student studentA;
cout <<Student::noOfStudents <<endl;
Student studentB;
cout <<Student::noOfStudents <<endl;
}
the output is 0
1
2
why ? in the previous code the value of static variable doesnt change but why does it change in this program ?
Jun 1, 2013 at 8:45pm
1
2
3
4
void func1(int i) {
	static int staticInt = i;
	cout << staticInt << endl;
}

The static variable is created and initialized the first time the function is called. Next time the function is called it will reuse the same object, having the same value as last time.
Jun 2, 2013 at 8:53am
ohh thanks :)
Jun 2, 2013 at 8:56am
Topic archived. No new replies allowed.