Thread: function pointer doesn't give expected output

  1. #1
    Registered User
    Join Date
    Jul 2018
    Posts
    81

    function pointer doesn't give expected output

    When I run code, function pointer doesn't give expected output


    Code:
     #include <stdio.h>
    
    void foo ( void )
    {    
        int a;
    	a = 20;
        printf(" a = %d\n", a);
    }
    
    
    int main()
    {
    	
    	void(*fp)(void) = &foo;
    
    
    	(*fp);
    
    
    	return 0;
    }
    I am expecting output it should print 20

  2. #2
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    You need to enable warnings, for example:
    -Wall -Werror -Wpedantic -std=c99
    main.c:17:5: error: statement with no effect [-Werror=unused-value]
    17 | (*fp);

    The correct way: fp(); on line 17

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Also, the function name is the entry point address, so you can drop the & and * operators:
    Code:
    ...
    void (*fp)(void) = foo;
    
    fp();
    ...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Break doesn't work the way I expected it to
    By GiladP in forum C Programming
    Replies: 3
    Last Post: 10-11-2020, 02:11 PM
  2. Replies: 5
    Last Post: 04-14-2016, 08:27 AM
  3. cin.get(); doesn't seem to be working as expected
    By Diablo84 in forum C++ Programming
    Replies: 5
    Last Post: 03-30-2005, 07:00 PM
  4. Why this do-while loop doesn't work as I expected?
    By Nutka in forum C Programming
    Replies: 4
    Last Post: 10-25-2002, 09:47 AM

Tags for this Thread