C++ Static Variables and Functions | Find output programs | Set 1

This section contains the C++ find output programs with their explanations on C++ Static Variables and Functions (set 1).
Submitted by Nidhi, on June 25, 2020

Program 1:

#include <iostream>
using namespace std;

int static fun(int x, int y)
{
    return (x + y);
}

int main()
{
    int K = 0;

    K = fun(10, 20);
    cout << K << endl;

    return 0;
}

Output:

30

Explanation:

Here, we created a static function taking two arguments x and y and returning the sum of both. And in the main() function, we created a local variable K to store the result returned by function fun() and then print K using cout.

Program 2:

#include <iostream>
using namespace std;

int* fun()
{
    static int a;

    a++;
    return &a;
}

int main()
{
    int* p;

    p = fun();
    p = fun();
    p = fun();
    p = fun();

    cout << "function called " << *p << " times";

    return 0;
}

Output:

function called 4 times

Explanation:

Here, we created a function that contains a static variable a and function returns an integer pointer.

Now, look at the main() function, here we created an integer pointer p that is storing the address returned by function fun(), after every function call, static variable increased, because the default value of the static variable is 0 and then its lifetime is in the whole program.

In the main() function we called function fun() 4 times, that's why it will print "function called 4 times" on the console screen.

Program 3:

#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;
}

Output:

function called 4 times

Explanation:

Here, we created a function that contains a static variable a, and the function returns an integer pointer.

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 increased because the default value of the static variable is 0 and then its lifetime is in the whole program.

In the main() function, we called function fun() 4 times, but the pointer has the address of the static variable in the first function call. As we know that, the lifetime of the main() function is in the whole program, that's why static variable will not release allocated space for the static variable then the address of a will not change and we got the latest value of static variable a, using the pointer.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.