3

so in my main function, I have a called function with arguments stored in a variable. I run my program, and the variable containing the function is executed. I thought that when I store functions or anything in a variable, then it shouldn't execute until I tell it to.

for example:

int cycle1 = cycleList(argument1, argument2);

this statement above is now executed on my screen. Is this a correct way to write code? I wanted to store the function in a variable, and later use the variable somewhere in my code.

3
  • 'I wanted to store the function in a variable, and later use the variable somewhere in my code.' Did you mean 'I wanted to store the functions result in a variable, and later use the variable somewhere in my code.' Then yes, it's correct. Commented Feb 7, 2014 at 13:25
  • Sounds like you're looking for something similar to a lambda or functor. Commented Feb 7, 2014 at 13:26
  • Thank you very much guys! Yeah, I was trying to store the results of the function into a variable. When I understand the basics, I'll look back at how to store a function instead of the result, but thanks for still answering and covering all possibilities from my question. Commented Feb 7, 2014 at 14:00

7 Answers 7

1

If you want to store a function, you need to make a pointer to the function, not call the function, which is what you're doing. Try this instead:

#include <functional>

std::function<int (int, int)> cycle1 = cycleList;

Or, if you don't have access to C++11, try this:

int (*cycle1)(int, int) = cycleList;

Then later you can call:

 cycle1(argument1, argument2);
Sign up to request clarification or add additional context in comments.

Comments

1

If you wanted to store the result of the function at that point in time in the program's runtime, then yes, you are doing it correctly.

Comments

0

Functions can accept parameters and can return a result. Where the functions are declared in your program does not matter, as long as a functions name is known to the compiler before it is called.

Let’s take a look at an example;

int Add(int num1, int num2)
    {
        return num1 + num2;
    }

    int main()
    {
        int result, input1, input2;

        cout << "Give a integer number:";
        cin >> input1;
        cout << "Give another integer number:";
        cin >> input2;

        result = Add(input1,input2);

        cout << input1 << " + " << input2 << " = " << answer;
        return 0;
    }

Here I defined Add() function before main() so main knows that Add() is defined. So in main() when add() calls it sends two parameter and get results with return num1+ num2 . Then it sends returned value to result.

Comments

0

As far as what I can get from your query is that you are calling a parameterized method in your class which is returning some value. You want to store the result of that method in a variable so that you can use it as per your need. But, you want to eliminate the overhead of computing that method even when you don't need it. It should be executed only when you require it or on the basis of a particular condition.

What I can suggest you in this case is, have this code in a condition. There must be an appropriate time or a satisfied condition when you want that method to execute and compute the result for you. For instance:

public class BaseCondition {
    public int compute(int a, int b) {
        return (a + b);
    }

    public boolean set(boolean flag) {
        flag = true;
        return flag;
    }

    public int subtract(int a, int b) {
        return (a - b);
    }

    public int callCompute(int a, int b) {
        boolean flag = false;
        int computedVal = 0;
        if (a < b || a == b) {
            flag = set(flag);
        }
        if (flag) {
            computedVal = compute(a, b);
        } else {
            computedVal = subtract(a, b);
        }

        return computedVal;
    }

    public static void main(String[] args) {
        BaseCondition obj = new BaseCondition();
        int a = 11;
        int b = 51;
        System.out.println("Result=" + obj.callCompute(a, b));

    }

}

Here, you can find compute will be called only on the basis of flag which is being set only when a condition is satisfied. Hope it helps :)

1 Comment

I have written a Java code for your problem. It won't vary much for C++. Apologies.
0

You can also do the following using auto's

#include <iostream>
using namespace std;

int Foo()
{
    return 0;
}

int main() 
{
    // your code goes here
    auto bar = Foo;
    return 0;
}

Comments

0

In C++, variables store values, not functions; and an expression that calls a function to get a value does so immediately. So your example calls the function to get an int value, then stores that value in the variable.

There are ways to do what you want:

// Store a lambda function object, capturing arguments to call it with.
// This doesn't call the function.
auto cycle1 = [=]{cycleList(argument1, argument2);};

// Call the function later. This calles 'cycleList' with the captured arguments.
int result = cycle1();

but you should probably learn the basics before doing this sort of thing.

Comments

0

Functions return results, and function objects can be stored (and copied around) themselves, including their arguments:

#include <iostream>

int cycleList(int arg1, int arg2) { return arg1 + arg2; }

struct cycleListObj
{
    int arg1, arg2;

    // constructor stores arguments for later use
    cycleListObj(int a1, int a2): arg1(a1), arg2(a2) {}

    // overload function call operator()
    int operator()() { return arg1 + arg2; }
};

int main()
{
    int result1 = cycleList(1, 1);   // stores 2 into result1
    cycleListObj fun(1, 1);          // defines a function object fun with arguments 1, 1
    int result2 = fun();             // calls the function object, and stores the result into result2
    std::cout << result1 << result2; // outputs 22
}

Live Example

As others have shown, the C++ Standard Library defines its own generic function object std::function, but for many purposes you can define them yourself as well.

You can also store function pointer, but then you still have to supply the arguments at the call site. With a function object, you can store the arguments first, and call it later.

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.