This section contains the C++ find output programs with their explanations on C++ Static Variables and Functions (set 2).
Program 1:
#include <iostream>
using namespace std;
int* fun()
{
static int a;
a++;
return &a;
}
int main()
{
int** p;
p = &(fun());
fun();
fun();
fun();
cout << "function called " << **p << " times";
return 0;
}
Program 2:
#include <iostream>
using namespace std;
int* fun()
{
static int a;
a++;
return &a;
}
static int a = 10;
int main()
{
int* p;
p = fun();
fun();
fun();
fun();
cout << "function called " << *p << " times";
return 0;
}
Program 3:
#include <iostream>
using namespace std;
class Sample {
static int A;
public:
Sample()
{
A++;
}
void display()
{
cout << A << endl;
}
};
int main()
{
Sample S;
S.display();
return 0;
}
Answer Program 1:
Output:
Explanation:
This code will generate an error because of the below statement,
p = &(fun());
In the above statement p is a chain pointer, but we are trying to get the address of address that does not exist.
Answer Program 2:
Output:
Explanation:
Here, we created a function that contains a static variable a and function returns an integer pointer.
And one more global static variable a is created and initialize with 10, here global and local both a are different variables.
Now, coming to the main() function, here we created an integer pointer p that is storing the address returned by function fun(), after every function call, the static variable gets increased, because the default value of the static variable is 0 and then its lifetime is in the whole program.
So, finally it will print "function called 4 times" on the console screen. After calling function fun() 4 times.
Answer Program 3:
Output:
Explanation:
This code will generate a syntax error (Undefined reference to 'Sample::A') because we declared a static variable, but we did not define it properly.
The below program will demonstrate how to define static members of the class?
Output: