C 中的函数声明和结构声明

发布于 2024-10-18 09:44:56 字数 548 浏览 4 评论 0原文

int f(struct r);
struct r
{
int a;
int b;
};

源文件中的上述代码片段会引发错误,

warning: its scope is only this definition or declaration,
which is probably not what you want for the line int f(struct r) 

并且在同一源文件中某处但在函数 f(struct r) 定义之前的以下代码片段

struct r emp;
f(emp);

会引发错误

error:type of formal parameter 1 is incomplete for the line f(emp)

,但当结构为替换为 typedef,没有这样的错误...

这个属性是否在使用特定于结构之前在函数声明中声明参数?

int f(struct r);
struct r
{
int a;
int b;
};

The above snippet in a source file throws an error that

warning: its scope is only this definition or declaration,
which is probably not what you want for the line int f(struct r) 

and the following snippet somewhere in the same source file but before the definition of function f(struct r)

struct r emp;
f(emp);

gives an error

error:type of formal parameter 1 is incomplete for the line f(emp)

but the same thing when the struct is replaced by typedef, there were no such such errors...

Is this property to declare an argument in a function declaration before its use is specific to structure alone?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我纯我任性 2024-10-25 09:44:57

尝试其他顺序:

struct r { int a; int b; };
int f(struct r);

如果需要在结构之前声明函数,请使用前向声明:

struct r;
int f(struct r);
...
struct r { int a; int b; };
int f(struct r anR)
{
    return anR.a + anR.b;
}

问题是在编译 int f(struct r); 期间,编译器看不到您的结构,因此它会创建一些临时结构。您稍后对结构的声明是从编译器的角度来看与临时结构无关的。

Try the other order:

struct r { int a; int b; };
int f(struct r);

If you need the function to be declared before the struct, use a forward declaration:

struct r;
int f(struct r);
...
struct r { int a; int b; };
int f(struct r anR)
{
    return anR.a + anR.b;
}

The problem is that during the compilation of int f(struct r); the compiler doesn't see your structure, so it creates some temporary structure instead. Your declaration of the structure later is from the compiler's point of view not related to the temporary one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文