0

A bit tedious to explain, but I will try. I have a function, which takes an address as input. Then instead of saving the variable first, so I can pass the address to that variable on to the function, I would like to enter the function directly as a parameter. Is there a way to do that?

Something like this:

#include <iostream>
#include "main.h"

using namespace std;

int main()
{
    printFunction(returnOne());
   return 0;
}

void printFunction(int *a) {
    cout << a << endl;
}

int returnOne() {
    return 1;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Spliid
  • 478
  • 1
  • 4
  • 12
  • 1
    Possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – πάντα ῥεῖ Jun 11 '16 at 17:37
  • 4
    Possible duplicate of [How do you pass a function as a parameter in C?](http://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c) – Marc Barbeau Jun 11 '16 at 17:41
  • @MarcBarbeau No the OP doesn't ask about function pointers. – πάντα ῥεῖ Jun 11 '16 at 17:52

1 Answers1

2

Well, obviously returnOne() doesn't match for passing into void printFunction(int*) regarding the return type, it should be something like:

int* returnOne() {
    static int one = 1;
    return &one;
}

or

int* returnOne() {
    return new int(1);
}

Another option would be to take the results address like

printFunction(&returnOne());
           // ^

but this yields in undefined behavior for an implementation like

int returnOne() {
    return 1;
}

since it takes the address of a temporary value.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190