1

I'm a bit new to c++ and I was trying to make a function that essentially adds the values given by another function for integer value inputs from the range start to end

int sum(int start, int end, int function(int input)){
      int output=0;
      for(int i=start; i<end; i++){
          output=output+function(i);}    //add the elements of the function from start to end
      return output;}

the above piece of code was the piece of code that I tried to run in visual studios but whenever I assign the variables some real values I get errors like type int incompatible with parameters of int(*)int(input) or something like that...I tried to get some help from the internet but most sources give very complicated code without really explaining how the code works...so I'd like to know how to do this and the reason behind why the way I did it doesn't work...using as little code as possible...and any explanation as to why an answer code would work will be appriciated as well...thanx a million in advance

edit: the function can be any function and the sum function takes in in the inputs given by the for loop, applies to the function and adds the values together...for example

      int function(x){ return 2*x;}
      
     //output to function(3)=6;
     //output to the sum(1,5,function(x))=2+4+6+8=10...(or at least thats what I want it to equal 

 
  • 1
    Could you post some input and expected output of `sum`? – John Park Jun 03 '22 at 06:44
  • 2
    Please update the question to show more context. How exactly are you calling this function? Consider manufacturing a [mre]. And don't paraphrase the error messages. Copy and paste it into the question. Often the exact wording and details matter. – user4581301 Jun 03 '22 at 06:44
  • You called the function when passing it rather than passing the function itself. You should just write its name. – molbdnilo Jun 03 '22 at 06:51
  • @JohnPark I eddited the question to add more information and example... – alienare 4422 Jun 03 '22 at 08:06
  • Did the reply work for you? You can accept it as an answer to change its status to Answered. – Minxin Yu - MSFT Jun 06 '22 at 02:34

1 Answers1

3

You can pass the function as a function pointer.

int sum(int start, int end, int (*function)(int))
{
      int output = 0;
      
      for(int i = start; i < end; i++){
          output = output + function(i);}    //add the elements of the function from start to end
      
      return output;
}

int anotherFunction(int input)
{
    //Do something here
    return input;
}

int main()
{
    std::cout << sum (1, 5, &anotherFunction);
    return 0;
}
ruvenij
  • 188
  • 6