简体   繁体   English

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

[英]Function Declarations and Structure declarations in C

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) 和以下代码段位于同一源文件中某个位置,但在定义函数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... 但是当用typedef替换struct时,同样的事情没有这样的错误...

Is this property to declare an argument in a function declaration before its use is specific to structure alone? 在使用函数特定于结构之前,此属性是否可以在函数声明中声明参数?

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); 问题是在编译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. 从编译器的角度来看,您以后对结构的声明与临时声明无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM