Hao Shen
Hao Shen

Reputation: 2735

How to modify a local static variable without calling the function where it is declared?

This is an interview question but I do not know how to do it.

Suppose we have a local static variable declared in a function. The interviewer asked me without calling the function, is it possible to modify it? I do not know how. But I suppose probably we can get the address of the local static variable by some way?

Upvotes: 1

Views: 138

Answers (2)

jdr5ca
jdr5ca

Reputation: 2819

I think this was a good interview question, but slightly intended to bias your answer towards the wrong answer.

The way you stated the question, it might lead you to think "how can I get around this language restriction?"

My answer would have been. "The purpose of the static local is to control scope. If we need broader scope, the variable should be correctly defined." In other words, my answer is don't do that.

Which way you headed with your answer is a useful measure of the fit to the environment. What will you do when faced with a barrier in the existing design: hack around it, or fix it?

Some elaboration that may help make my view clear:

You're in the break room and the interviewer asks "see that candy vending machine - is it possible to get candy out without putting money in?" Your mind starts spinning "if I use the coffee stirrers I might be able to..." The next day, you're still working out how to get that candy out of the machine.

A different interviewer might have asked the same question "How do you get candy out of the candy machine?" You say "put money in"

It is the same question about how you deal with an existing interface, but one misleads you.

Upvotes: 1

Brave Sir Robin
Brave Sir Robin

Reputation: 1046

It's allowed to return a pointer to an object with static storage, e.g.

#include <stdio.h>

int *foo(void) {
    static int x;
    printf("%d\n", x);
    return &x;
}

int main(void) {
    int *p = foo();
    *p = 10;
    foo();
    return 0;
}

Will print:

0
10

Alternatively, you could of course pass a pointer to pointer and store it there instead of returning it.

Upvotes: 3

Related Questions