Oria Gruber
Oria Gruber

Reputation: 1533

Basic function pointer misunderstanding

I have the following code:

#include <stdio.h>
#include <conio.h>

int fun1 (int);
int fun2 (int);
int fun3 (int);

int (*fun4) (int) = fun1; // 1

void main()
{
    int (*fun4) (int) = fun2; // 2
    printf ("%d\n", fun4(3));
    printf ("%d\n", fun3(3));
    getch();
}

int fun1 (int x)
{
    return x+1;
}

int fun2 (int x)
{
    return 2*x;
}

int fun3 (int x)
{
    return fun4(x);
}

It yields the output:

6
4

I'm not sure why that happens.

At the line where //2 is written, we defined that fun4 points to fun2. so from then on, when i write fun4(x) its the same as writing fun2(x). I'm not sure why the second print yields 4.

Could anyone explain why this happens?

Upvotes: 0

Views: 61

Answers (4)

Oktalist
Oktalist

Reputation: 14714

If you change your code like this:

int (*fun4) (int) = fun1; // 1

void main()
{
    fun4 = fun2; // 2
    printf ("%d\n", fun4(3));
    printf ("%d\n", fun3(3));
    getch();
}

Then it will behave as you expected. The change is on the line marked // 2. Instead of declaring a different variable called fun4 at local scope, it will assign a different value to the existing global fun4.

Upvotes: 0

haccks
haccks

Reputation: 106012

so from then on, when i write fun4(x) its the same as writing fun2(x). I'm not sure why the second print yields 4.

No.

int (*fun4) (int) = fun2; // 2  

is visible inside the main scope only. fun4 is pointer to fun2 only inside the main. Outside of main's scope fun4 is pointer to fun1.
When you call fun4(x) in fun3 then it is equivalent to fun1(x)

Upvotes: 2

Hemant Gangwar
Hemant Gangwar

Reputation: 2272

You have two definition of fun4 one is local and another one is global. If we replace definition of fun4 your code look like this:

#include <stdio.h>
#include <conio.h>

int fun1 (int);
int fun2 (int);
int fun3 (int);

int (*fun4) (int) = fun1; // 1 (global definition)

void main()
{
    int (*fun4) (int) = fun2; // 2 (local definition)
    printf ("%d\n", fun2(3)); //! Since fun4(local) pointing to fun2
    printf ("%d\n", fun3(3));
    getch();
}

int fun1 (int x)
{
    return x+1;
}

int fun2 (int x)
{
    return 2*x;
}

int fun3 (int x)
{
    return fun1(x); //! Since fun4(global) pointing to fun1
}

Note: Please refer to the comments for the changes

Upvotes: 1

afenster
afenster

Reputation: 3608

In your example fun3 calls fun4 and the definition of fun3 does not know anything about the local fun4 variable. To make it clear, the assignment fun2 = fun4 is a pointer assignment, not name assignment. When you call this function it will not search it by name, but only by pointer, and the pointer assigned is the one that points to fun1.

Upvotes: 1

Related Questions