Where to declare structures inside main () or outside main ()?

Line 1: 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; } 

Case 2: declared inside main() , indicating an error

[Error] type 'main () :: prod' without the link used to declare the function 'int billamt (main () :: prod *)' with the binding [-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; } 
+5
source share
3 answers

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

  • First of all, I think that you meant "define," not "declare."

  • Secondly, there is no rule as such, you can determine where you want. It is all a matter of definition.

    • If you define a structure inside main() , the scope is limited only to main() . Any other function cannot see this definition and, therefore, cannot use this structure definition.

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

+10
source

This is due to the fact that when defining the structure inside the main function, it is determined only in the area of ​​the main function, therefore the billamt function cannot know about it.

+1
source

The structure is a similar array, only the main difference in the array can contain only values ​​of the same type, but the structure can have different types of values, so if you need to implement the structure globally (globally, I mean that it can be used in any other function too) define it outside the main one, and if you want to use your structure only in the main function, define it inside it. Happy coding :-)

+1
source

All Articles