Question

I would like to return a function with a variable inside it that I can initialize inside the function that returns it. Possible, or no?

int get_char (char *c)
{
    static circular_queue *cir; // this needs to be initialized in the function below
    if (circular_queue_empty(cir))
        return 0;
    else
        *c = circular_queue_pop(cir);
    return 1;
}

int (*generate_get_char(circular_queue *cir)) (char *c)
{
    // do something to set cir
    return &get_char;
}

I am passing the pointer to getchar into an API that I do not control so I cannot change the format of get_char; that being said, is there a better way of doing this as I am pretty sure the above is not possible. (I would rather not use a static global, but thats all I can think of doing).

TY

Was it helpful?

Solution

Variables which have static storage allocation are default initialized to zero. Therefore, the following statements are effectively equivalent.

static circular_queue *cir;
// equivalent to
static circular_queue *cir = 0;
// equivalent to
static circular_queue *cir = NULL;

The variable cir has function scope, i.e., it can be accessed only in the function get_char. Therefore, the answer to your question

I would like to return a function with a variable inside it that I can initialize inside the function that returns it. Possible, or no?

is no. You need a global variable which is visible to both the functions get_char and generate_get_char. Also, note that a function name implicitly converts to a pointer. Therefore, the following are equivalent -

return &get_char;
// equivalent to
return get_char;

OTHER TIPS

This is not possible - cir is accessible only from get_char and there is no way to access it from outside. You need a static global visible by both functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top