2

Can someone explain me this program please

#include <stdio.h>

void print(void)
{
   printf("g");
}

int main()
{
    void(*message)(void);

    print();    // i have doubt here it g

    message = print; // now here why it is printin g again

    (*message)();

    return 0;
}

this program brings a void function at first which is just printf now when we go to main function the first line indicates the pointer message which is void it didn't get the cose afterwards

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 3
    _Side note:_ Using a function pointer, you can invoke it [as you've done] with: `(*message)();` But, you can also use a slightly cleaner/simpler version: `message();` The compiler will infer that this means `(*message)();` – Craig Estey Aug 07 '22 at 01:48
  • Possibly a duplicate of "[How do function pointers in C work?](/q/840501/90527)" – outis Aug 08 '22 at 06:48

2 Answers2

8

You're calling print twice: once directly:

print(); 

And once through a function pointer:

message = print; 
(*message)();
dbush
  • 205,898
  • 23
  • 218
  • 273
1

The reason that it is printing "g" twice is because you are calling the function print() both before and after you assign the function pointer.

You are essentially doing this:

print(); // this calls the function print()

message = print; // this assigns the function pointer message to point to the function print()

(*message)(); // this calls whatever function the function pointer message is pointing to, which happens to be print()
vatsal mangukiya
  • 261
  • 2
  • 14