Tuesday, July 14, 2009

Do structures in C always have to be defined globally?

Can you define a structure in a function or do you have to put it up above the main()?

Do structures in C always have to be defined globally?
structs are variables and, consequently, can be defined anywhere in a program.





It is, generally, bad practice to use global variables in C - I would stay away from even thinking about them.





Use $DEFINE macros for any global values.
Reply:You can declare a structure in a local scope. It would have been faster to test it than to ask here. Or better yet, look up a C reference.
Reply:Well, you can always try it and find out for yourself. :)


I don't think it will make any difference, as long as you define a structure BEFORE using it.


Structure definitions are for the compiler's sake, not your program's. However, variables can be defined locally or globally and their placement makes a lot of difference to how the variables are compiled.


Type definitions can also be put anywhere, as long as you define them before you use them.


Remember that you have to ALLOCATE the structure, and wherever you allocate it, it will affect the program code just like with other variables.
Reply:While this would be a easy question to answer...simply declare a struct inside int main or main (not sure of the syntax on C) and see if it would compile correctly...I believe the question would be WHY you would want to, think about it...why are you using your struct statement, if you put inside a main function wouldn't you have to actually pass the struct as an argument EACH time you wanted to use it inside a new function?


No comments:

Post a Comment