本文介绍了在哪里声明结构,在 main() 内部还是在 main() 外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例 1:main() 之外声明的结构工作正常

Case 1: structure declared outside main() working fine

#include<stdio.h>
#include<conio.h>
struct prod
{
    int price,usold;
};
int main()
{
    struct prod *p,a;

    int billamt(struct prod *);
    int bill;
    printf("enter the values \n");
    scanf("%d%d",&p->price,&p->usold);
    bill=billamt(p);
    printf("bill=%d",bill);
    getch();
}
int billamt(struct prod *i)
{
    int b;
    b=(i->price*i->usold);
    return b;
}

情况 2:main() 中声明,给出错误

Case 2: declared inside main() giving error

[错误] 类型 'main()::prod' 没有链接用于声明函数 'int billamt(main()::prod*)' 与链接 [-fpermissive]*

#include<stdio.h>
#include<conio.h>
int main()
{
    struct prod
{
    int price,usold;
};


    struct prod *p,a;

    int billamt(struct prod *);
    int bill;
    printf("enter the values \n");
    scanf("%d%d",&p->price,&p->usold);
    bill=billamt(p);
    printf("bill=%d",bill);
    getch();
}
int billamt(struct prod *i)
{
    int b;
    b=(i->price*i->usold);
    return b;
}

推荐答案

  1. 首先,我认为你的意思是定义",而不是声明".

  1. First thing, I think you meant "define", not "declare".

其次,没有规则,你可以定义任何你想要的地方.一切都与定义的范围有关.

Second, there is no rule as such, You can define wherever you want. It is all about the scope of the definition.

  • 如果您在 main() 内部定义结构,则作用域仅限于 main().任何其他函数都无法看到该定义,因此无法使用该结构定义.

  • If you define the structure inside main(), the scope is limited to main() only. Any other function cannot see that definition and hence, cannot make use of that structure definition.

如果您在全局范围内定义结构(即,在 main() 或任何其他函数之外,就此而言),该定义在全局范围内可用,并且所有函数都可以查看并使用结构定义.

If you define the structure in a global scope, (i.e., outside main() or any other function, for that matter), that definition is available globally and all the functions can see and make use of the structure definition.

这篇关于在哪里声明结构,在 main() 内部还是在 main() 外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:19