Determining a smaller integer from the two given integers using pointer to a function and if statement C++ code sample

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Determining a smaller integer from two given integers using a pointer to a function and if statement in C++ programming

To show: How to use a pointer to a function and if statement to determine the smaller integer from the two given integers in C++ programming

 

// a pointer to a function, determining a smaller number from the given two numbers

#include <iostream>

using namespace std;

 

// function prototypes

float minimum(float, float);

// (*ptr) is a pointer to function of type float

float (*ptr)(float, float);

 

void main(void)

{

float x1, x2, small;

 

// assigning address of minimum() function to ptr

ptr = minimum;

// prompt user for input

cout<<"\nEnter two numbers, separated by a space: ";

// read and store

cin>>x1>>x2;

// call the function pointed by ptr small has the return value

small = (*ptr)(x1, x2);

cout<<"\nsmaller number is "<<small<<endl;

}

 

// find the smaller integer

float minimum(float y1, float y2)

{

if (y1 < y2)

return y1;

else

return y2;

}

 

Output example:

 

Enter two numbers, separated by a space: 200 100

smaller number is 100

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index