Introduction to C + + Classic-Example 5.8-using pointer functions for operations

Source: Internet
Author: User

1: function pointer pointer to function memory, a function at compile time is assigned to a portal address, the function of the entry address is called the function pointer. You can use a pointer variable to point to a function, and then call this function from that pointer variable.

A function can return an integer value, a character value, a real value, and so on, or it can return a pointer-type data, that is, an address, and the type of the return value is a pointer type. Returns a pointer function that is worthy of a function abbreviation.

The general form of defining pointer functions is:

Type name * Function name (parameter list)

For example, define a pointer to a function with two parameters and a return value and a function with the same return value parameter list as follows:

int sum (int x,inty);

int *a (int,int);

A=sum;

A function pointer can point to a function that returns a value and a parameter list, when a function pointer is used, as follows:

int c,d;

*a (C,D);

2: Use the function pointer for the calculation, the code is as follows:

//ConsoleApplication5.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;intAvgintAintb);intSumintAintb);intMain () {intiwidth, Ilenght, Iresult; Iwidth=Ten; Ilenght=Ten; int(*pfun) (int,int);//Defining function Pointerscout <<"the Pfun points to avg"<<Endl; Pfun=avg; Iresult= (*pfun) (iwidth, ilenght);//calling functions with function pointerscout <<"Execution Result:"<< Iresult <<Endl; cout<<"Pfun points to the sum"<<Endl; Pfun=sum; Iresult= (*pfun) (iwidth, ilenght);//calling functions with function pointerscout <<"Execution Result:"<< Iresult <<Endl; return 0;}intSumintAintb) {    returnA +b;}intAvgintAintb) {    return(A + B)/2;}
View Code

Operation Result:

Introduction to C + + Classic-Example 5.8-using pointer functions for operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.