abhey
abhey

Reputation: 5

c assignment operator =

Can anyone pl. explain how the following c program works: Specifically how function 'fun' is assigned to (*p)() = fun; I need to know how compiler compiles this code.

#include<stdio.h>
int fun(); /* function prototype */

int main()
{
    int (*p)() = fun;
    (*p)();
    return 0;
}
int fun()
{
    printf("Hello World\n");
    return 0;
}

Upvotes: 0

Views: 135

Answers (2)

001
001

Reputation: 13533

Each function exists in memory somewhere. The statement:

int (*p)() = fun;

is assigning the memory location of the function fun to p. Then the line:

(*p)();

is calling the function that exists at the memory location that p is pointing to.

The Interweb is full of info on "function pointers."

Upvotes: 4

ouah
ouah

Reputation: 145919

If you look at the code generated by gcc (with -O0):

    movl    $_fun, -4(%ebp)
    movl    -4(%ebp), %eax
    call    *%eax 

It stores the address of the fun function in a variable in the stack and then simply indirectly calls this address.

Upvotes: 2

Related Questions