Originally Posted by
richdb
My first question is can that local variable declared in a function be passed as an argument to another function?
C passes by value, so the value of the variable is returned rather than the variable itself. Thus it doesn't matter whether the variable is in scope or not -- what you get back is a copy. Here's a simple example of pass by value:
Code:
/* ... */
void
open_file (FILE *fp, char *path, char *mode)
{
/* open the file */
}
/* ... */
FILE *fp; char *fn = "myfile"; char *mode = "w";
open_file (fp, fn, mode);
/* ... */
This looks like it will work, and (all things being equal) the file will open with no error ... but the fp in the function is not the same variable the caller is using. After the call, the fp you want to use is not initialized -- a copy of it was.
However, it will work if you return fp and use it to initialize the fp of the caller ...
Code:
/* ... */
FILE *
open_file (char *path, char *mode)
{
FILE *fp;
/* open the file */
return fp;
}
/* ... */
FILE *fp; char *fn = "myfile"; char *mode = "w";
fp = open_file (fn, mode);
/* ... */
My other question is similar. With the functions themselves, I know that a function can contain another function that was defined after it.
You don't need to fuss over the sequence of your functions when you can simply prototype them up top.