2009년 12월 27일 일요일

[C++] Function Pointer(1) (Global function & using array)



* Introduction *
- A week ago, to parse network packets I used to do 'if' for all case. During optimizations, I turned from 'if' to 'function pointer with map'. I'm going to write about the function pointer as known as possible.


* Basic usage (code) *
#include <iostream>
void     Function1() ;
int        Function2(int _x, int _y) ;
int main()
{
    //////////////////////////////////////////////////////////////////////////
    // Test inside Main function
        // for void Function1() ;
    void (*PtrFunc1)() ;
    PtrFunc1 = Function1 ;
    PtrFunc1() ;
        // for int Function2(int, int) ;
    int  (*PtrFunc2)(int, int) ;
    PtrFunc2 = Function2 ;
    int result = PtrFunc2(20, 10) ;
    std::cout << "Result = " << result << std::endl ;
    return 0 ;
}
void Function1()
{
    std::cout << "Function1" << std::endl ;
}
int  Function2(int _x, int _y)
{
    std::cout << "Function2" << "  X = " << _x << "  Y = " << _y << std::endl ;
    return (_x + _y) ;
}






* Using with array *
#include <iostream>
void    ArrayFunction1(int _x) ;
void    ArrayFunction2(int _x) ;
void    ArrayFunction3(int _x) ;
int main()
{
    int choice ;
    void (*f[3])(int) = {ArrayFunction1, ArrayFunction2, ArrayFunction3} ;
    std::cout << "Enter a number between 0 and 2, 3 to end: " ;
    std::cin >> choice ;
    while (choice >= 0 && choice < 3) {
        (*f[choice])(choice) ;
        std::cout << "Enter a number between 0 and 2, 3 to end: " ;
        std::cin >> choice ;
    }
    return 0 ;
}
void ArrayFunction1( int _x )
{
    std::cout << "ArrayFunction1: _x = " << _x << std::endl ;
}
void ArrayFunction2( int _x )
{
    std::cout << "ArrayFunction2: _x = " << _x << std::endl ;
}
void ArrayFunction3( int _x )
{
    std::cout << "ArrayFunction3: _x = " << _x << std::endl ;
}







Reference : How To C++ Program 4th edition



- ps.
This blog is for my English abilities, and I'm not good at communicating in English. If you see grammatic, syntax or logical errors, or if you can't understand clearly, PLEASE COMMENT ON IT. Your comments definitely help me, and I really appreciate this. :)

- Written by Gordon

댓글 없음:

댓글 쓰기