A community member has associated this post with a similar question:
Why the user-defined function needs to be before the main function for a function pointer to work

Only moderators can edit this content.

Why the user-defined function needs to be before the main function for a function pointer to work

Debojit Acharjee 455 Reputation points
2023-07-26T13:52:36.9+00:00

IN the following program why the user-defined function needs to be before the main function in order to run the program. When I put the function after the main function, it doesn't work. Why?

This one works:

#include <stdio.h>

int add(int a, int b)
{
    int c;

    c = a + b;

    return c;
}

int main()
{
    int a, b, sum;
    int (*ab)(int, int) = &add; // Declaration and initialization of function pointer

    sum = (*ab)(1, 2); // Dereferencing of function pointer

    printf("1 + 2 = %d", sum);

    return 0;
}

But why this one doesn't work?

#include <stdio.h>

int main()
{
    int a, b, sum;
    int (*ab)(int, int) = &add; // Declaration and initialization of function pointer

    sum = (*ab)(1, 2); // Dereferencing of function pointer

    printf("1 + 2 = %d", sum);

    return 0;
}

int add(int a, int b)
{
    int c;

    c = a + b;

    return c;
}
Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
{count} votes

1 answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    1 deleted comment

    Comments have been turned off. Learn more