Thread: correct way to call function through function pointer

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    correct way to call function through function pointer

    Hi,
    I'm reading one article about function pointers and I found this simple code:
    Code:
    #include <stdio.h>
    
    typedef int (*pFunc) (int, int);
    int sum (int, int);
    int diff (int, int);
    
    int main ( void )
    {
    	pFunc pfArr[2];
    
    	pfArr[0] =  &sum; /* correct way*/
    	/*pfArr[0] =  sum; Possible incorrect way ???*/ 
    	pfArr[1] = &diff;
    
    	printf("%d",pfArr[0](2,3));
    	printf("%d",(*pfArr[0])(2,3)); /*correct way*/
    
    	return 0;
    }
    
    int sum (int a, int b)
    {
    	return a + b;
    }
    
    int diff (int a, int b)
    {
    	return a - b;
    }
    I read there about "correct ways" to call function through function pointer.

    I tried both solutions and both works fine.
    Code:
    printf("%d",pfArr[0](2,3));
    printf("%d",(*pfArr[0])(2,3)); /*correct way*/
    What I'm not sure is whether both solutions are valid according to the Standard. Please, can you comment this

    Thanks

    - Micko
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    http://www.eskimo.com/~scs/C-faq/q4.12.html
    They're both valid - though I prefer the decluttered versions using no &*()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    Thank you master Salem!
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What is a virtual function pointer?
    By ting in forum C++ Programming
    Replies: 4
    Last Post: 03-05-2008, 02:36 AM
  2. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  3. Replies: 7
    Last Post: 07-04-2007, 12:46 PM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM