pointers to functions.

im completely new in c++
i was trying to write a function which returns mod of difference of two input numbers ie.(z=|x-y|) im having compilation errors.can someone help me?
thanx in advance.
here u go:

#include <iostream>

using namespace std;
int sub_1(int x, int y)
{
return x-y;
}
int sub_2(int x,int y)
{
return y-x;
}
int main()

{
int (*sub_3)(int, int);
int a,b;
cin>>a>>b;
if(a>=b)
{
sub_3(int, int)=&sub_1;
}
else
{
sub_3(int ,int)=&sub_2;
}
cout<<(*sub_3)(a,b);

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	int (*sub_3)(int, int);
	int a, b;
	cin >> a >> b;
	if (a >= b)
	{
		sub_3 = sub_1;
	}
	else
	{
		sub_3 = sub_2;
	}
	
	cout << sub_3(a,b) << endl;
}
thanks
i think we can even write it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	int (*sub_3)(int, int);
	int a, b;
	cin >> a >> b;
	if (a >= b)
	{
		sub_3 =& sub_1;
	}
	else
	{
		sub_3 =& sub_2;
	}
	
	cout << *sub_3(a,b) << endl;
}


where does it differ?
Last edited on
I don't think there's any difference for functions, it just saves you some typing :-) Think of what it means to call a function, you're not using an object, just referring to some code in memory, i.e. an address.

"int sub_1(int, int)" is a function, when you use just bare "sub_1", it means you're using the address of the function. You can also do it your way.

For regular (non-function) objects, the "&" is necessary:

1
2
3
4
5
6
7
8
9
10
int d = 15;
int a = 10;
int b = a; // contents of a copied to b
int *c = &a; //c contains the address of object a. The & is necessary
*c *= 2; // a now contains 20
c= &d; // c now holds a different address, *c == 15;
void (* myfree)(void *) = free; // "void free(void *)" is a function, the "&" is not necessary
void (* myotherfree)(void *) = &free; // the "&" is not prohibited either
myfree(previously_malloced_pointer);
myotherfree(another_previously_malloced_pointer);

Last edited on
Topic archived. No new replies allowed.