Skip to content

Instantly share code, notes, and snippets.

@peta909
Created February 27, 2019 14:54
Show Gist options
  • Save peta909/64189e781857735f8c515c402f935817 to your computer and use it in GitHub Desktop.
Save peta909/64189e781857735f8c515c402f935817 to your computer and use it in GitHub Desktop.
// Function_Pointers.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int add()
{
int i = 10;
cout << "inside add" << endl;
return i = i + i;
}
double divide()
{
double j = 7;
return j / 9;
}
int square(int x)
{
return x * x;
}
void NonRetFunc()
{
cout << "Non Ret Func" << endl;
//return 0;
}
double bigfunc(int(*fcnPtr1)(), double(*fcnPtr4)())
{
return ((*fcnPtr1)() + (*fcnPtr4)());
}
int main()
{
cout << "Function pointers" << endl;
if (add)//as the check is against the addr of add()
{
cout << "This is always true!" << endl;
}
if (int i = add() > 100)//check is done against ret value of add()
{
cout << "> 100" << endl;
}
else
cout << "<< 100" << endl;
// function pointer assignments
int(*fcnPtr1)() = add; // okay
//int(*fcnPtr2)() = divide; // wrong -- return types don't match!
double(*fcnPtr4)() = divide; // okay
//fcnPtr1 = square; // wrong -- fcnPtr1 has no parameters, but hoo() does
int(*fcnPtr3)(int) = square; // okay
void(*fcnPtr5)() = NonRetFunc;
double(*fcnPtr6)(int(*fcnPtr1)(), double(*fcnPtr4)()) = bigfunc; // use if a func ptr is used to access bigfunc
cout << "add 10 and 10 is " << (*fcnPtr1) << endl;//ret the addr of add
cout << "add 10 and 10 is " << (*fcnPtr1)() << endl;
cout << "divide 7 with 9 is " << (*fcnPtr4)() << endl;
cout << "square 9 is " << (*fcnPtr3)(9) << endl;
(*fcnPtr5)();
cout << "bigfunc result is " << (*fcnPtr6)(add, divide) << endl;
cout << "bigfunc result is " << bigfunc(add, divide) << endl;
getchar(); //added to prevent console from closing after code is executed.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment