#include <iostream>
using namespace std;
void increment(int *n){ //declare argument of the functon as pointer
*n+=1;
cout<<"In function: "<<*n<<endl;
}
int main()
{
int x=5;
increment(&x); //passing the address of the variable to the function
cout<<"In main: "<<x<<endl;
}
// c++ function as pointer syntax
type(*function_name)(params...){
// body
}
//why do we use pointers:
1)pass values by refrence to a function
2)return multiple values from a function
3)use pointers in combinational with arrays
4)dynamic memory allocation
5)use pointers in a base class in order to access object of derived class (Smart pointers)
// Here's a macro I use to define a type.
// You're welcome to use it, but I'll also show how the type is defined.
#define d_typedef_func_ty(return_z, name, ...) typedef return_z (*name)(__VA_ARGS__);
d_typedef_func_ty(int, int_2i_f, int, int); // creates a int(*)(int, int) function pointer
// which is equivelant to the following:
typedef int(*int_2i_f)(int, int);
#include <iostream>
using namespace std;
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
ptr = &d;
cout << "Enter feet: ";
cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;
cout << "Displaying information." << endl;
cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
return 0;
}
//example that uses pointer as parameter
// function definition to swap the values.
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}