我正在尝试执行以下程序,但反过来编译器生成错误。我假设程序是正确的,并且我在程序的开头包含了函数原型(prototype)。但是没有函数原型(prototype),程序可以正常工作而不会出错。 (即第一个函数定义,然后是主函数)。我想知道我的理解哪里不正确。
#include <stdio.h>
void func(struct tag v);
struct tag {
int i;
char c;
};
/*
void func(struct tag v)
{
printf("%d %c\n", v.i, v.c);
return;
}
*/
int main()
{
/*struct tag {
int i;
char c;
};*/
struct tag var = {2, 's'};
func(var);
return 0;
}
void func(struct tag v)
{
printf("%d %c\n", v.i, v.c);
return;
}
输出:root@bhaskar:/home/bhaskar/Downloads/practice/cpractice/cindepth/struct# gcc p11_excer_1_4.c
p11_excer_1_4.c:3:18: warning: ‘struct tag’ declared inside parameter list will not be visible outside of this definition or declaration
void func(struct tag v);
^~~
p11_excer_1_4.c: In function ‘main’:
p11_excer_1_4.c:17:7: error: type of formal parameter 1 is incomplete
func(var);
^~~
p11_excer_1_4.c: At top level:
p11_excer_1_4.c:22:6: error: conflicting types for ‘func’
void func(struct tag v)
^~~~
p11_excer_1_4.c:3:6: note: previous declaration of ‘func’ was here
void func(struct tag v);
^~~~
最佳答案
颠倒声明的顺序:
struct tag {
int i;
char c;
};
void func(struct tag v);
更好的是,重新排序所有内容,这样您就不需要提前声明,您只需定义:#include <stdio.h>
struct tag {
int i;
char c;
};
void func(struct tag v)
{
printf("%d %c\n", v.i, v.c);
}
int main()
{
struct tag var = {2, 's'};
func(var);
return 0;
}
编译器需要在使用之前了解结构等。它不能跳过以了解更多信息。为避免过度复制,通常建议传入指向结构的指针,如下所示:
void func(struct tag* v)
{
printf("%d %c\n", v->i, v->c);
}
然后当被调用时:func(&var);
而这个struct
是一个相当微不足道的大小,通常情况并非如此,因此熟悉此技术很重要。 struct
并不少见重达 1MB 或更多,具体取决于内容,复制它可能会很痛苦。也没有必要,也没有理由
return
末尾有void
功能。这是默认行为。
关于c - 警告 : ‘struct tag’ declared inside parameter list will not be visible outside of this definition or declaration void func(struct tag v);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64106548/