Passing values from a function to another function - c++

I'm new in C++ programming world and I have not understood yet if it's possible (and how) to use an output from a function as input to another function.
#include <iostream>
using namespace std;
int func(int l, int m) {
int x = l * m;
return x;
}
int code(x?) {
...
}
I would like to use output from func (the value x) as an input for code.
Is it possible? How could I do that?
Thanks for the help
EDIT 1:
Really thanks for the answers. Is it possible also to pass values between functions using pointers?

Functions only "have" values while they are executed.
You can either call the first from the second funtion,
or call the first function, read the return value into a variable and give that value as parameter to the second,
or call the second and give one of its parameters directly as return value from a call to first function.
Here are some examples of the three options, using 1,2,3 as arbitrary integers.
Variant 1:
int func(int l, int m) {
int x = l * m;
return x;
}
int code(void) {
int ValueFromOtherFuntion=func(1,2);
return 3;
}
Variant 2:
int func(int l, int m)
{
int x = l * m;
return x;
}
int code(int XfromOtherFunction)
{
return 3;
}
int parentfunction(void)
{
int ValueFromOtherFuntion=func(1,2);
return code(ValueFromOtherFunction);
}
Variant 3:
int func(int l, int m)
{
int x = l * m;
return x;
}
int code(int XfromOtherFunction)
{
return 3;
}
int parentfunction(void)
{
return code(func(1,2));
}

Yes, what you are looking for is called function composition.
int sum(int a, int b)
{
return a + b;
}
int square(int x)
{
return x*x;
}
int main()
{
std::cout << square(sum(5, 4)); //will calculate (5+4)squared
}

When you write the functions, assume that you already have all the input and proceed just writing what you want that function to do.
As to when you use that function, use "nested functions" or a function inside a function as such:
code(func(l, m));
Function func will execute first and return the value x, thus leaving you with code(x) which will execute after. Its like pealing an onion: one layer to the other.

#include <iostream>
int func(int l, int m) {
int x = l * m;
return x;
}
void code(int x) { // argument type is the same as the return type of func
std::cout << x;
}
int main (){
int result = func(1 ,2); // either store it
code(func(1, 2)); // or pass it directly.
std::cout << result;
return -1;
}

You can call it in your main function (or in any other within scope for what matters):
code(func(l,m))

Related

How to use a variable from other functions

int calculateX()
{
int x;
cout<<"Enter value for x: ";
cin>>x;
return x;
}
int anotherFunction()
{
/////
}
int main()
{
calculateX();
anotherFunction();
return 0;
}
This is an example on a code. How do can I possibly use the input from the user in the calculateX() function into the function anotherFunction() ?
You have to use function parameters:
int calculateX()
{
int x;
cout<<"Enter value for x: ";
cin>>x;
return x;
}
int anotherFunction(int x)
{
/////
}
int main()
{
int x = calculateX();
anotherFunction(x);
return 0;
}
what you need is either a pass by value , which is already answered or a global variable like this
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int anotherFunction()
{
cout << g;
}
int main () {
// Local variable declaration:
int a, b;
a = 10;
b = 20;
g = a + b;
anotherFunction();
return 0;
}
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
You must declare the variable x global (outside the calculateX() function), so that anotherFunction() can see it. If you define the variable x inside the calculateX() function, it will be deleted after exiting the function.
int x;
int calculateX()
{
cout<<"Enter value for x: ";
cin >> x;
return x;
}
int anotherFunction()
{
/////
}
int main()
{
calculateX();
anotherFunction();
return 0;
}
Function generally has return type before it's name. For Example :
int calculateX() {
int x;
cout<<"Enter value for x: ";
cin>>x;
anotherFunction(x)
return x;
}
int is here return type.And you are calling two functions from your main function. calculateX has a variable of type int named x. So, you can't access x from outside of calculateX scope. But you can return it to your main function and store it in a different variable so that It becomes available in main function. Once It becomes available, you can send it as argument to another function . In your case It should be like this :
int anotherFunction(int valueFromMain)
{
std::cout << valueFromMain << std::endl;
}
int main(){
int returnedFromCalculateX = calculateX(); //You have returned value available on main Function
anotherFunction(returnedFromCalculateX); //Send It to anotherFunction(pass by value)
return 0;
}
You can also send the value as a reference. That needs a bit higher understanding. Please Check : https://www.w3schools.com/cpp/cpp_function_reference.asp for more details.

Is there a way to explicitly call optional arguments in c++?

When I create a function such as:
int addThree(int x=1, int y=1, int z=1)
I want to call the function such that it uses the default arguments for x and z, but not y.
Some attempts have been addThree(5,,5) and addThree(5,NULL,5), but neither work effectively.
The default arguments must be at the last of your list, so do as follows
int addThree(int y , int x = 1, int z = 1)
{
//some stuff
return someInt;
}
, hence you can call it as
int ans = addThree(4);
Default arguments in C++, need to be specified in immediate succession, and cannot be succeeded by a non-default parameter.
So, something like
int sum(int x = 0, int y, int z = 0) {
return (x + y + z);
}
is forbidden in C++
The function needs to be as follows:
#include <iostream>
int sum(int x, int y = 0, int z = 0) {
return (x + y + z);
}
int main() {
std::cout << sum(1) << "\n";//calls sum(1,0,0)
std::cout << sum(1,2) << "\n";//calls sum(1,2,0)
return 0;
}
However, while specifying default arguments, you always need to take care in function overloading. The overloaded functions cannot be called ambiguously..
So a code like:
#include <iostream>
int sum(int x, int y = 0, int z = 0) {
return (x + y + z);
}
float sum(int x, float y = 0.0, float z = 0.0) {
return (float(x) + y + z);
}
int main() {
std::cout << sum(1) << "\n";
return 0;
}
does not compile and righty produces ambiguity error, as the compiler does not understand
Whether it should call the first sum, or the second sum.
If you're consistently passing a value for one parameter and using the defaults for the others, you can rearrange the parameters to the one you need to pass is first, and the ones for which you use defaults come later. But that only works if it's essentially always the same ones for which you supply a value vs. use the defaults.
Otherwise, if you need something similar to the basic capability badly enough, you can pass an instance of a class, and have that class implement the named parameter idiom.
class triplet {
int x_ {1};
int y_ {1};
int z_ {1};
public:
triplet &x(int val) { x_ = val; return *this; }
triplet &y(int val) { y_ = val; return *this; }
triplet &z(int val) { z_ = val; return *this; }
int x() const { return x_; }
int y() const { return y_; }
int z() const { return z_; }
};
int addThree(triplet const &t) {
return oldAddThree(t.x(), t.y(), t.z());
}
int ans = addThree(triplet().x(4));
This lets you use the defaults for as many or few of the values you need as you want, and override only those that you actually want to. On the other hand, it does add a fair amount of syntactic overhead, so you have to want the capability pretty badly to bother.

function pointer for different functions with different data types or parameter

i have this code which uses a function pointer to point 3 functions sum, subtract, mul. it works well. but now the problem is that i have functions with different no.of parameters and different data types. how to implement this.
int add(int a, int b)
{
cout<<a+b;
}
int subtract(int a, int b)
{
cout<<a-b;
}
int mul(int a, int b)
{
cout<<a*b;
}
int main()
{
int (*fun_ptr_arr[])(int, int) = {add, subtract, mul};
unsigned int ch, a = 15, b = 10,c=9;
ch=2;
if (ch > 4) return 0;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
The simple answer is that technically you can't do this. You could do some manipulations using an array as input for all these functions, but you will still have to know exactly what to pass to each function. From a software engineering perspective, you should not do this - I suggest you take a look at the nice answers here: C++ Function pointers with unknown number of arguments
A slightly different approach using objects to implement the required behavior. In order to have a truly generic kind of solution, we need to use Interfaces.
Dismantle the data and operation i.e keep them separately.
//Interface which describes any kind of data.
struct IData
{
virtual ~IData()
{
}
};
//Interface which desribes any kind of operation
struct IOperation
{
//actual operation which will be performed
virtual IData* Execute(IData *_pData) = 0;
virtual ~IOperation()
{
}
};
Now, every operation knows the kind of data it work on and will expect that kind of data only.
struct Operation_Add : public IOperation
{
//data for operation addition.
struct Data : public IData
{
int a;
int b;
int result;
};
IData* Execute(IData *_pData)
{
//expected data is "Operation_Add::Data_Add"
Operation_Add::Data *pData = dynamic_cast<Operation_Add::Data*>(_pData);
if(pData == NULL)
{
return NULL;
}
pData->result = pData->a + pData->b;
return pData;
}
};
struct Operation_Avg : public IOperation
{
//data for operation average of numbers.
struct Data : public IData
{
int a[5];
int total_numbers;
float result;
};
IData* Execute(IData *_pData)
{
//expected data is "Operation_Avg::Data_Avg"
Operation_Avg::Data *pData = dynamic_cast<Operation_Avg::Data*>(_pData);
if(pData == NULL)
{
return NULL;
}
pData->result = 0.0f;
for(int i = 0; i < pData->total_numbers; ++i)
{
pData->result += pData->a[i];
}
pData->result /= pData->total_numbers;
return pData;
}
};
Here, is the operation processor, the CPU.
struct CPU
{
enum OPERATION
{
ADDITION = 0,
AVERAGE
};
Operation_Add m_stAdditionOperation;
Operation_Avg m_stAverageOperation;
map<CPU::OPERATION, IOperation*> Operation;
CPU()
{
Operation[CPU::ADDITION] = &m_stAdditionOperation;
Operation[CPU::AVERAGE] = &m_stAverageOperation;
}
};
Sample:
CPU g_oCPU;
Operation_Add::Data stAdditionData;
stAdditionData.a = 10;
stAdditionData.b = 20;
Operation_Avg::Data stAverageData;
stAverageData.total_numbers = 5;
for(int i = 0; i < stAverageData.total_numbers; ++i)
{
stAverageData.a[i] = i*10;
}
Operation_Add::Data *pResultAdd = dynamic_cast<Operation_Add::Data*>(g_oCPU.Operation[CPU::ADDITION]->Execute(&stAdditionData));
if(pResultAdd != NULL)
{
printf("add = %d\n", pResultAdd->result);
}
Operation_Avg::Data *pResultAvg = dynamic_cast<Operation_Avg::Data*>(g_oCPU.Operation[CPU::AVERAGE]->Execute(&stAverageData));
if(pResultAvg != NULL)
{
printf("avg = %f\n", pResultAvg->result);
}
If you have the following functions
int f1(int i);
int f2(int i, int j);
You can define a generic function type like this
typedef int (*generic_fp)(void);
And then initialize your function array
generic_fp func_arr[2] = {
(generic_fp) f1,
(generic_fp) f2
};
But you will have to cast the functions back
int result_f1 = ((f1) func_arr[0]) (2);
int result_f2 = ((f2) func_arr[1]) (1, 2);
Obviously, it does not look like a good way to build a program
To make code look a little bit better you can define macros
#define F1(f, p1) ((f1)(f))(p1)
#define F2(f, p1, p2) ((f2)(f))(p1, p2)
int result_f1 = F1(func_arr[0], 2);
int result_f2 = F2(func_arr[1], 1, 2);
EDIT
Forgot to mention, you also have to define a type for every type of function
typedef int (*fi)(int); // type for function of one int param
typedef int (*fii)(int, int); // type for function of two int params
And to then cast stored pointers to those types
int result_f1 = ((fi) func_arr[0]) (2);
int result_f2 = ((fii) func_arr[1]) (1, 2);
Here is a complete example
#include <iostream>
typedef int (*generic_fp)(void);
typedef int (*fi)(int); // type for function of one int param
typedef int (*fii)(int, int); // type for function of two int params
#define F1(f, p1) ((fi)(f))(p1)
#define F2(f, p1, p2) ((fii)(f))(p1, p2)
int f1(int i);
int f2(int i, int j);
int main()
{
generic_fp func_arr[2] = {
(generic_fp) f1,
(generic_fp) f2
};
int result_f1_no_macro = ((fi) func_arr[0]) (2);
int result_f2_no_macro = ((fii) func_arr[1]) (1, 2);
int result_f1_macro = F1(func_arr[0], 2);
int result_f2_macro = F2(func_arr[1], 1, 2);
std::cout << result_f1_no_macro << ", " << result_f2_no_macro << std::endl;
std::cout << result_f1_macro << ", " << result_f2_macro << std::endl;
return 0;
}
int f1(int i)
{
return i * 2;
}
int f2(int i, int j)
{
return i + j;
}
The code above produces the following output
4, 3
4, 3

How can I access a member of a class from a function via pointer?

I wish to
create an array of class/struct items (c1)
then create an array of pointer to the original array (*cp1), which can be sorted
then access members of the class from within a function.
However I'm getting stuck at the initial function call.
Here's my basic code:
struct Car
{
int speed;
};
Car c1[5];
Car *cp1[5];
int main() {
for (int i=0;i<5;i++) {
c1[i].speed = i;
cp1[i] = &c1[i];
}
garage(cp1, 5);
}
void garage(Car **ar, int n) {
int p = (*ar[n / 2])->speed;
}
First of all, your garage function is not known to the compiler at the place where you call it, since it is defined below main. To fix it, either place the function definition above main, or introduce it with a prototype.
Second, at the line int p = (*ar[n / 2])->speed;, *ar[n/2] is not a pointer, so you should use . instead of ->, as in int p = (*ar[n / 2]).speed;
Funcion garage must be declared before you can refer it.
void garage(Car **ar, int n);
int main()
{
//...
}
void garage(Car **ar, int n) {
//...
}
Function main in C++ shall have return type int
int main()
{
//...
}
And within the function the correct expression will look
void garage(Car **ar, int n) {
int p = (*ar )[n / 2]).speed;
}
Or
void garage(Car **ar, int n) {
int p = ar[n / 2]->speed;
}
Or
void garage(Car **ar, int n) {
int p = ( *ar[n / 2] ).speed;
}
struct Car
{
int speed;
};
Car c1[5];
Car *cp1[5];
void garage(Car **ar, int n); // forward declare garage
int main()
{
for (int i=0;i<5;i++) {
c1[i].speed = i;
cp1[i] = &c1[i];
}
garage(cp1, 5);
}
void garage(Car **ar, int n) {
int p = ar[n / 2]->speed; // -> dereferences the pointer, you don't need to
}

callback vs lambda

Suppose I have the following code that I wish to refactor:
int toFuture()
{
precalc();
int calc = 5 * foobar_x() + 3;
postcalc();
return calc;
}
int toPast()
{
precalc();
int calc = 5 * foobar_y() - 9;
postcalc();
return calc;
}
In classic-C, I would refactor this code into a worker() which accepts a function pointer that does the calculation: common code in worker(), specific code provided by function pointer.
With C++11, should I be using a lambda instead? If so, how would I implement it, in this case?
Edit: it just crossed my mind that a template may also work. How would a template implementation compare against the other two?
One approach:
template<typename CalcFuncT>
int perform_calc(CalcFuncT&& calcfunc)
{
precalc();
int const calc = std::forward<CalcFuncT>(calcfunc)();
postcalc();
return calc;
}
int main()
{
perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture
perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast
}
If you are wanting a template approach using C++11 features, that could look as simple as:
template<typename FuncType>
auto calculation(FuncType&& func) -> decltype(func())
{
precalc();
auto ret = func();
postcalc();
return ret;
}
You would then simply call your calculation function and pass it either a lambda, a functor, or a function-pointer. Your only souce of difficulty in this instance would be if you passed a function that had a void return-type ... in that case you will get a compiler error (which is a good thing vs. a runtime error).
I'd say you're refactoring from the wrong side:
struct CalcGuard {
CalcGuard() { /* replaces precalc() */ }
~CalcGuard() { /* replaces postcalc() */ }
};
int toFuture()
{
return CalcGuard(), calc = 5 * foobar_x() + 3;
}
int toPast()
{
return CalcGuard(), calc = 5 * foobar_y() - 9;
}
There is a C/C++ way to do this, and a C++11 way. Neither way involves lambdas or templates.
The C/C++ way:
double MyFunc (int x, float y) { return x + y ; }
int main()
{
double (*pf) (int, float) ;
pf = MyFunc ;
pf (101, 202.0) ;
}
The C++11 way:
#include <functional>
double MyFunc (int x, float y) { return x + y ; }
int main()
{
std::function<double (int, float)> f ;
f = MyFunc ;
f (51, 52.0) ;
}
In either case, you just pass pf or f to your refactored function as a parameter. Using lambdas or templates is overkill here.