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);
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);