c - where to declare structures, inside main() or outside 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 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; } 

case 2: declared inside main() giving error

[error] type 'main()::prod' no linkage used declare function 'int billamt(main()::prod*)' linkage [-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 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; } 

where declare structures, inside main() or outside main()?

  1. first thing, think meant "define", not "declare".

  2. second, there no rule such, can define wherever want. scope of definition.

    • if define structure inside main(), scope limited main() only. other function cannot see definition , hence, cannot make use of structure definition.

    • if define structure in global scope, (i.e., outside main() or other function, matter), definition available globally , functions can see , make use of structure definition.


Comments