0

I'm a beginner but what I'm trying to do is getting the value of two pointers and saving the 'action' of their addition. I thought pointer to function would work but can't find how to initialize a pointer to a function with it's parameters. Something like this.

int foo(int *a, int *b){return *a + *b;}
//main

int *a = new int, *b = new int;
*a = 10;
*b = 20;
int (*ab)(int *a, int *b) = foo(a, b); // here I try to save it like it is but I can't.
                                       // otherwise It would be like calling a function to get the result,
                                       // my idea was to save it to a variable.    
std::cout << ab << std::endl;

*a = 2000;
  
std::cout << ab << std::endl; // so the 'value' of ab would change here.

I was trying to think this to avoid having to change values that depend on one another. Maybe there's an easier way but I haven't got to it yet.

1 Answer 1

1

You can't have a pointer depend on the values of multiple other pointers the way you want. But you could write a lambda that captures the dependent variables by reference, and returns the value returned by the call to foo. Any changes to the values pointed at by the pointers will be reflected in what the lambda returns. You'll need to use call syntax to access the value.

auto ab = [&] { return foo(a,b); };  // define ab

std::cout << ab() << std::endl;      // use ab

Here's a demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.