开发者

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 defin开发者_如何学Pythonition 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜