Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pass address of a function return value as function parameter

I have two functions:

void a(int * p);
int b();

Is it possible to pass the address of the return value of function b to function a something like this: a(&b()) ?

like image 506
papaiatis Avatar asked Jun 28 '13 15:06

papaiatis


2 Answers

A compound literal seems to do the trick (requires a C99 compiler):

int a()
{
    return 5;
}

void b(int *a)
{
    // do something with a
    printf("%d\n", *a);
}

int main(void)
{
    b(&(int){ a() });
}

Output is 5.

like image 165
dreamlax Avatar answered Nov 15 '22 04:11

dreamlax


Only by using a temporary variable:

int result = b();
a(&result);

EDIT: Apparently there's also a way to do this using a compound literal, described in another answer here.

like image 32
James McLaughlin Avatar answered Nov 15 '22 05:11

James McLaughlin