I have a function defined with several parameters passed by value. Both the function and inputs for the parameters depend on a common global variable. I need some way to get my function to re-evaluate the inputs of its parameters while executing within its own scope. Here is a simplified version of the code.
#include <iostream>
using namespace std;
int Sum(int arg1, int from, int to);
int i;
int func();
int main(int argc, char *argv[])
{
Sum(func(), 0, 10);
return 0;
}
int Sum(int arg1, int from, int to)
{
int out = 0;
for (i = from; i <= to; i++)
{
out += arg1;
cout << "arg1 = " << arg1 << ", out = " << out << endl;
}
return out;
}
int func()
{
return i;
}
Some highlights:
* Here I am trying to update the input values for parameter arg1 on function Sum().
Normally, I would solve this problem by defining the parameter by reference (in this case, the parameter is arg1 in function Sum).
However, because the method in which I use this function normally involves combining multiple input values inline, I have to pass by value.
Is there some way to define a temporary unnamed function inline with the inputs for Sum? Then I could pass parameters by reference and solve my troubles. Or any other ideas for how to make this work?
Thanks!
This is a place you could use a function pointer. Instead of passing func(), you pass simply func, and call it from within your function:
int Sum(int (*func_arg1)(void), int from, int to)
{
int out = 0;
for (i = from; i <= to; i++)
{
int arg1 = func_arg1();
out += arg1;
cout << "arg1 = " << arg1 << ", out = " << out << endl;
}
return out;
}
The syntax for function pointers is a bit unusual in C and C++. The declaration int (*func_arg1)(void) declares a symbol named func_arg1 that is a pointer to a function taking no arguments, but returning int. In this case, that symbol is also the first argument of Sum.
The only other changes you need to make to your program are the prototype for Sum to match the function above, and to call Sum as follows:
Sum(func, 0, 10);
Related
When passing a value to a function with multiple arguments which contains some default values how would I let my function know that this value is supposed to be for the last argument?
For example in the code
int myFun(int a, int b=2,ofstream &file) {
file<<"Hello please write this to a file"<<"\n";
int r;
r=a/b;
return (r);
}
int main () {
ofstream file("input.txt");
cout << myFun(12,3,file)<< '\n';
cout << myFun(20, ,file) << '\n'; //This doesn't work
return 0;
}
How would I let my program know that the value 4 is supposed to be for C and not for B?
You cannot do that. Default arguments have to be provided starting from the right. You cannot have default arguments for the second but none for the third.
One workaround is to encapsulte the parameters in a data structure:
struct myFunParameters {
int a = 0;
int b = 2;
std::ofstream& file;
};
And change signature to:
int myFun(myFunParameters f);
The caller can then use the defaults or provide custom values in any order they wish.
Alternatively remove the default arguments and use an overload:
int myFun(int a, int b,ofstream &file);
int myFun(int a,ostrstream& file) { return myFun(a,2,file); }
A beginner's question I couldn't find answered online, likely because I don't know the terminology.
I want to call one of a list of procedures based on a computed index value. That is, given a '1', invoke firstProc(), '2' invokes secondProc() and so on.
All the procedures are void functions with no arguments.
I can implement that with switch/case, but what I'd prefer is something like:
void* action[2] {*firstProc, *secondProc};
(This compiles, but warns: invalid conversion from 'void (*)()' to 'void*')
and then later:
action[get_index()]();
The compiler objects that 'action' can't be used as a function.
This must be possible, right? I've tried several variations but I can't get past the use of the selected ('action[index]') as a function.
There are two equivalent ways to do what you want. The explanation is given as comments in the code snippets.
Method 1
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything
void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything
//create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
void (*arr[2])() = { a, b};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 1 can be executed here.
In method 1 above void (*a)() = foo; means that a is a pointer to a function that takes no parameter and also does not return anything.
Similarly, void (*b)() = foo2; means that b is a pointer to a function that takes no parameter and also does not return anything.
Next, void (*arr[2])() = { a, b}; means that arr is an array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter.
Method 2
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
//create array(of size 2) that can hold pointers to functions that does not return anything
void (*arr[2])() = { foo, foo2};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 2 can be executed here.
You need the correct syntax for your function pointer array. void(*func_ptr[])().
Example:
void func1() { std::cout << "Hallo" << std::endl; }
void func2() { std::cout << "World" << std::endl; }
// if you need a different signature for your functions like:
int func3(int n) { std::cout << "n1 " << n << std::endl; return n*2; }
int func4(int n) { std::cout << "n2 " << n << std::endl; return n*3; }
int main()
{
// array of function pointer which
// have no parameter and void as return value
void(*func_ptr[])()={ func1, func2 };
for ( unsigned int idx = 0; idx<2; idx++ )
{
func_ptr[idx]();
}
// array of function pointers with int return value and int as
// parameter
int(*func_ptr2[])(int)={ func3, func4 };
for ( unsigned int idx = 0; idx<2; idx++ )
{
std::cout << "retval: " << func_ptr2[idx](6) << std::endl;
}
}
I've stopped using function pointers (though they still can be useful).
I usually use std::function (and lambdas) when working with functions
Code for arrays of functions then look like this.
I used std::vector but std::array for fixed size should work fine too.
#include <vector>
#include <functional>
#include <iostream>
void some_function()
{
std::cout << "some function\n";
}
int main()
{
// std::function, abstraction of a function, function signature = template parameter, so void () is function returning a void, no parameters
// std::vector, runtime resizable array
// constructor : 4 time a lambda function printing out hello world.
std::vector<std::function<void()>> functions(4, [] { std::cout << "Hello World!\n"; } );
// easy syntax to assign an existing function to an index
functions[1] = some_function;
// replace a function in the vector with another one (lambda)
functions[2] = [] { std::cout << "booh\n"; };
// call function at index 0
functions[0]();
std::cout << "\n\n";
// or loop over all the functions and call them (classic for loop)
for (std::size_t n = 0; n < functions.size(); ++n) functions[n]();
std::cout << "\n\n";
// or loop over all the functions (range based for loop)
for (const auto& function : functions) function();
return 0;
}
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.
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);
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.
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.
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 :)
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;
}
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.
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.
I made a program that calls this function. I know this because "Int Strength has been called" appears in the output box. However, it will not change the values that I tell it to do.
I want it to get integer values from main(), then use them and return the new values.
I am using a header file that only contains "int strength(int a, int s, int i)"
int strength(int a, int s, int i)
{
using namespace std;
cout << "Int Strength has been called" << endl;
a = a + i;
s = s - i;
return a;
return s;
}
Multiple errors. Firstly, if you want the arguments to be modified (more precisely, the modification being effective out of the scope of the function), you have to pass the values by reference:
int strength(int &a, int &s, int &i)
Second, you seem to be concerned about return a; return s; returning two values. It doesn't - the very first return encountered exits the function immediately.
The values only change within the function. Variables are passed by value not reference.
Use references as the parameters.
int strength(int& a, int& s, int& i)
You're passing by value. You need to pass a pointer to the memory allocated in the caller that contains the data you wish to modify.
void strength(int *a, int *s, int i)
{
using namespace std;
cout << "Int Strength has been called" << endl;
*a += i;
*s -= i;
}
Then call it thusly:
a = 1;
s = 2;
i = 3;
strength(&a, &s, i);
I am not sure how to have a function that receives a class object as a parameter. Any help? Here is an example below.
#include<iostream>
void function(class object); //prototype
void function(class tempObject)
{
//do something with object
//use or change member variables
}
Basically I am just confused on how to create a function that will receive a class object as its parameters, and then to use those parameters inside the function such as tempObject.variable.
Sorry if this is kind of confusing, I am relatively new to C++.
class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.
e.g.
class ANewType
{
// ... details
};
This defines a new type called ANewType which is a class type.
You can then use this in function declarations:
void function(ANewType object);
You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.
If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.
void function(ANewType& object); // object passed by reference
This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.
[* The class keyword is also used in template definitions, but that's a different subject.]
If you want to pass class instances (objects), you either use
void function(const MyClass& object){
// do something with object
}
or
void process(MyClass& object_to_be_changed){
// change member variables
}
On the other hand if you want to "pass" the class itself
template<class AnyClass>
void function_taking_class(){
// use static functions of AnyClass
AnyClass::count_instances();
// or create an object of AnyClass and use it
AnyClass object;
object.member = value;
}
// call it as
function_taking_class<MyClass>();
// or
function_taking_class<MyStruct>();
with
class MyClass{
int member;
//...
};
MyClass object1;
At its simplest:
#include <iostream>
using namespace std;
class A {
public:
A( int x ) : n( x ){}
void print() { cout << n << endl; }
private:
int n;
};
void func( A p ) {
p.print();
}
int main () {
A a;
func ( a );
}
Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.
I was asking the same too. Another solution is you could overload your method:
void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);
in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself
void remove_id(EmployeeClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(ProductClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(DepartmentClass _obj) {
int saveId = _obj->id;
...
};
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below.....
(p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}