Skip to main content

Problem #2

Posted in

static int a = 0, b = 3;
 
int change_a() { return ++a; }
int change_b(int x) { return b+=x; }
 
void func(int x)
{
    static int aa = change_a();
    static int bb = change_b(x);
}
 
int main()
{
    func(1);
    func(3);
    func(5);
    func(9);
 
    return 0;
}

Q: What are the values of a and b after the execution of main() ?
A: a = 1, b = 4;

Explanation: Static variables are initialized only once. func will be called 4 times, as expected, but change_a and change_b will be called only once (because of static variables aa and bb).

Note: If you move declaration of aa and bb outside of func then a will be equal to 4 and b will be equal to 21.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
aborigi_a_: