You are right that returning a pointer to a soon-to-be-destroyed variable is not correct. You can solve this problem by returning a pointer to a memory region allocated with malloc (although the caller must remember to free this memory), or by taking a pointer as the argument to w_insc
, and then filling in the pointer with the returned value.
However, there are much broader issues with trying to implement the w_insc
function. There is no way for w_insc
to know what the caller expects. Just because the caller casts the return value of w_insc
to int
doesn't allow w_insc
to know that it should return an int
. The only information that a C function has available to it is its set of parameters, plus any global variables in the program (and global variables are usually the wrong way to solve your problem). Note that a C function has no way of knowing what the caller will do with its return value. As a result, there is no way to write w_insc
to take no parameters and return something scanned correctly based on some cast that the caller makes.
You could add a parameter to w_insc
, making the declaration into
int w_insc(const char *format, ...)
This allows the caller to pass in a format string and a series of arguments detailing what they expect to get out of standard input. However, with this implementation you have just wrapped scanf with ... another function that looks just like scanf.
My advice: use the standard library functions, since they are standardized, and someone reading your code will know instantly what it means, rather than having to read through the definition of a nearly-trivial wrapper like the w_insc
you have described.