c - 警告 : ‘struct tag’ declared inside parameter list will not be visible outside of this definition or declaration void func(struct tag v);

标签 c struct parameters scope namespaces

我正在尝试执行以下程序,但反过来编译器生成错误。我假设程序是正确的,并且我在程序的开头包含了函数原型(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/

相关文章:

c - 任何类型的一般排序,与结构作斗争

c++ - 作为参数传递的数组的 sizeof 的奇怪行为

c - OpenSSL/OCSP 装订;如何在传递给 SSL_CTX_set_tlsext_status_cb(...) 的回调中访问 SSLContext?

c - 读取两个整数并找出第一个整数的所有小于第二个整数的正倍数

c++ - "int a;"是 C 和 C++ 中的声明还是定义?

java - JUnit parameterized Tests 获取测试后的参数

VB.NET - 将事件作为参数传递

scanf 格式字符串中的 "%.70s"会导致意外行为吗?

c - 不兼容的指针类型 - C

c - 如何在不使用通用指针的情况下引用指向数据或数据的指针?