开发者

How to obtain value from a void function? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I want to use a predefined function which is called in the main function. This predefined function obtains some values from a packet received, lets say a timestamp from the recei开发者_JAVA技巧ver which I would like to use in the main function. However the problem is that this predefined function is of void type and can't return anything. I am thinking about using the concept of global variables because local variables would fail in this case. Can someone please give an example for implementing this thing?


If the function is predefined it must already have a predefine way of returning results.

One possible way for a void function to return results is if one of its parameters is a pointer. Then it can put results in the object pointed to by that pointer.


Use such functions:

void f(int *a)
{
    *a = 5;
}

It will modify a, but will return void.

If using c++ it's better to use reference:

void f(int &a)
{
    a = 5;
}


you should try to avoid using global variables, since you will have to make an extra effort to make them thread safety and also they are kind of a bad practice (make the code difficult to follow and easy to introduce bugs, etc).

you may use a pointer or change the return value (either way, you will have to change the function prototype). another solution would be to define another function that calls the "offending" one (the one you're trying to change) and process the result there, then continue to the original function with the original parameters, so your function a() will return whatever you need, but call b() inside (the one returning void)


If your asking for how to use a global:


int gGlobalValue;

void funcion()
{
  int returnValue = 1; // Or whatever
  gGlobalValue = returnValue;
}

This is a non maintainable, poor way of doing what you want, but here it is.


If you want some generic callback, you can use e.g. this prototype:

void (*callback)(void *);

And return the appropriate data via the parameter (as passed by reference).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜