Forward declaration of function types in C

王林
Release: 2024-02-08 22:00:12
forward
764 people have browsed it

C 中函数类型的前向声明

php editor Zimo introduces to you the forward declaration of function types in C language. In C language, forward declaration of a function type is a way of declaring a function without defining it. With forward declarations, we let the compiler recognize and use these functions in subsequent code without having to define them ahead of time. This is very useful in solving the problem of functions calling each other, especially when writing large programs. By using forward declarations of function types, we can improve the readability and maintainability of the code, making the code more modular and structured. Let’s take a closer look at this important C language feature.

Question content

I want to declare a recursive function type (a function that declares itself) in C.

With a language like Go I can do:

type F func() F

func foo() F {
  return foo
}
Copy after login

If I try to do the same thing in C:

typedef (*F)(F());
Copy after login

I get the following error from GCC:

main.c:1:14: error: unknown type name ‘F’
    1 | typedef (*F)(F());
Copy after login

This makes sense since F does not exist when it is used. Forward declaration can solve this problem, how to forward declare function type in C?

Solution

C Recursive type definitions are not supported.

Exception: You can use a pointer to a struct type that has not been declared, so the struct type can contain a pointer to a struct of the struct type being declared.

Also, you can obviously use a struct type that has not yet been declared as the return value of a function. So this is close to what you want:

// This effectively gives us
// typedef struct { F *f } F( void );

typedef struct S S;

typedef S F( void );

struct S {
   F *f;
};

S foo() {
   return (S){ foo };
}

int main( void ) {
   F *f = foo;
   printf( "%p\n", (void*)f );

   f = f().f;
   printf( "%p\n", (void*)f );
}
Copy after login

The above is the detailed content of Forward declaration of function types in C. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!