Retrieving a value from a void function.

D

Don

I am a beginner in C. A student I should say. Is it possible to
retrieve a value from a void function? A have a void function that
reads a string or number from a file. I call that function from main
and want to set char* x or int x equal to what is read. How does that
work?
Thank you
 
J

Jyotirmoy

Hi,

You can't read back a value from a void function. For your problem, you
have two options. You've to chage the function declaration so that it
returns the desired value (int or char *) or you have to pass a pointer
as an argument to the void function. Look at the following snippets:

Option 1:
---------------
main(){
int x;
x = foo();
printf("%d\n", x);
}

int foo(){
int y;
/*read from the file and store the value in y*/
return y;
}

Option 2:
-----------------
main(){
int x;

foo(&x);
printf("%d\n", x);
}

void foo(int *x){

/*read from file and store it in x*/
return;
}
 
W

Walter Roberson

You can't read back a value from a void function. For your problem, you
have two options. You've to chage the function declaration so that it
returns the desired value (int or char *) or you have to pass a pointer
as an argument to the void function.

Another possibility suitable in -some- instances is to set a variable
that is in the scope of both the called and calling function; that
could be file scope or a "global variable".

And a different hack that is sometimes used in difficult situations is,
on systems that support it (as it is not pure C) to set an environment
variable.

In between, there are possibilities involving temporary files, or
pipes, or shared memory segments, or STREAMS... definitely not all
portable.
 
D

Don

The argument to the void function was indeed a pointer. Thank you
kindly. That was a life saver.
 
D

dot

I am a beginner in C. A student I should say. Is it possible to
retrieve a value from a void function? A have a void function that
reads a string or number from a file. I call that function from main
and want to set char* x or int x equal to what is read. How does that
work?

The answer is "pointers"...

First, if you are writing this function yourself... the easy thing to do is
rewrite it so it returns a pointer to your string or int variable.

If for some reason it has to be a "void" return and not a "void pointer"
return you can always write it to pass in a pointer as a parameter
indicating where you want the result placed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,427
Latest member
HildredDic

Latest Threads

Top