Home > Enterprise >  Why it is printing g two times?
Why it is printing g two times?

Time:08-08

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

CodePudding user response:

You're calling print twice: once directly:

print(); 

And once through a function pointer:

message = print; 
(*message)();

CodePudding user response:

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()
  •  Tags:  
  • c
  • Related