现在的位置: 首页 > 综合 > 正文

Function Pointers —–PART 1

2013年06月09日 ⁄ 综合 ⁄ 共 1524字 ⁄ 字号 评论关闭
Introduction
  
In a previous series of articles named " Pointer Perfect," I looked at how data stored in computer memory is accessible through pointer, The code you write for your application in the form of functions (these can be global or class member functions) is very much accessible through pointers in the same way, and i will introduce you to the syntax and usage of these function pointers in this article.
Function pointers are great for implementing callbacks and are very useful when you want to introduce late binding in your application.They help you parse configuration files,help you read protocols and can help you store a function call in an object when you want to delay or record the call(very useful in an undo/redo system).
A Quick Example
There is nothing like a quick example to take you straight to the heart of a topic. Here is a simple code example that use a function pointer.
// main.cpp
    #include
    int IncOne(int var){
         return ++var;
    }
    int main(int argc,char *argv[])
    {
          //creating pointer to function
         int (*inc_one)(int)=&IncOne;
         //use the function the standard way
         int result=IncOne(1);
        (void) printf("result is :%d/n",result);
        //utilize that function pointer
         result =inc_one(1);
        (void) printf("result is : %d/n",result);
        return 0;
   }
 When you run this simple example, you will notice that both times the resulted is '2'-- as expected,of course, So what has the compiler come up with for us? Let's take a peek into the debugger at the value stored in inc_one.
       int (*inc_one) (int)=&IncOne;
      00411A9E   mov  dword ptr [line_one],offset IncOne     (411523h)
 It holds the address 0x00411523,add loking at the memory at that position we find the following line:
    


抱歉!评论已关闭.