[SOLVED] C language do structures always have to be defined globally ?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
C language do structures always have to be defined globally ?
All the C language examples I see have structures defined
globally. I have read global variables are to be avoided
and would like to define my structures within a function or
within main(). Can this be done ?
How can I do this when a function prototype must be defined
with a pointer to a structure ? Function prototypes must
be defined globally, right ? So how can I define this
prototype when the structure is NOT defined globally ?
#include <stdio.h>
struct tag { char first[40];
char second[40];
int speed; };
struct tag butter;
void show_butter( struct tag *b ); /* display butter */
int main(void)
{
------ I want to define and declare the structure here
or inside a function yet to be written -------
struct tag *ptr;
ptr = & butter;
----- more code loading structure with data ---
show_butter( ptr );
return 0;
}
I hope I got the idea across and my code isn't to sloppy.
Any ideas would be welcome. I'm using gnu C in Slackware.
This says that bah is now a type-name that refers to a particular struct. That is to say: "I, the programmer, do hereby inform you, the computer, that, by virtue of mine own imperial decree, a variable of type bah is a structured type whose component elements forsooth shall be as follows ..."
The syntax of "C" was envisioned somewhat for convenience as opposed to rigor. Messers. Kernighan and Ritchie made some decisions that just seemed good to them at the time. (They knew a great deal about language design, of course, but nevertheless, there does come a point in the design process where you have to toss that coin.)
This typedef syntax is, I think, quite suitable, because you can now say things like: bah *thisbah = &thatbah, where you have elsewhere also defined thatbah to be of the same type, bah.
Last edited by sundialsvcs; 02-17-2012 at 04:16 PM.
All the C language examples I see have structures defined
globally. I have read global variables are to be avoided
and would like to define my structures within a function or
within main(). Can this be done ?
Yes, it can be done. You can define a struct inside a function. You can then only use that struct inside that function.
But by defining it globally, you are not creating a global instance of it. Except for keeping your global namespace clean by not creating definitions of something you only use in a limited scope, there is no real benefit I know of of defining structs locally.
Quote:
Originally Posted by zeelog
How can I do this when a function prototype must be defined
with a pointer to a structure ? Function prototypes must
be defined globally, right ? So how can I define this
prototype when the structure is NOT defined globally ?
As I said, if you define structure locally, you can only use it in the function in which it is defined, so unless you are defining the function inside the function where the struct is defined (which in C is not possible), you can not use that struct as an argument or return type of any function. If you want to do that, declare the struct globally.
Defining a struct itself is usually done globally because there is usually no need to specifically confine the definition to a particular scope. But this is the definition of the struct itself, NOT the definition of a variable having the type of that struct, and using memory space.
A definition that takes up space can be defined globally. Unfortunately, too many programmers do define things globally out of laziness or other reasons, when there is otherwise no technical reason to do so. But sometimes there are good reasons for it. I just often see it done when there are not any good reasons for it.
What you should do is just define the "shape" of the structure globally, like:
Code:
struct my_node {
struct my_node *next;
struct my_node *prev;
double number;
} /* do not put a variable name here */;
If you are making a project in multiple files, this should be placed in a header that all the files needing it will include (so it is defined in one common place to avoid the definition in multiple places getting out of sync).
Then you define the function as returning a pointer to this struct, or whatever. And then you define variables which are actual data of this struct type, or pointers to such, in various places (in main() or in any function).
Do not define space with the "shape definition". Define variables (or functions) using it in the scope they need to be in.
As I said, if you define structure locally, you can only use it in the function in which it is defined, so unless you are defining the function inside the function where the struct is defined (which in C is not possible), you can not use that struct as an argument or return type of any function. If you want to do that, declare the struct globally.
To my knowledge, defining local structures and/or local (nested) functions is not the preferred way of programming in C (as opposed to, say, scheme or ruby). You can make a function local to a compilation unit by defining is as static. Such a function is not visible outside of the file it is defined in. Static functions has some other advantages.
Well, of course all variables can be local or global; structs are no different from any other. But I'm a bit worried by the initial premise here:
Quote:
I have read global variables are to be avoided.
If a variable is to be accessed by more than one function, then it must be global (except for Gnu C, which allows non-local variables, including functions, but that's another story).
A variable should be local if it is a scratch variable, used only in one function, say for calculation, and not needed after the function closes (if it is needed with the same value in a later call of the same function it can indeed be static, but here the variable value, but not its name, is stored with the global variables). Otherwise, if functions p() and q() both use a global variable a for internal calculation and we have code like
Code:
void p()
{
...
a=7;
q();
...
}
then the call of q() may alter a and upset the remaining code in p(). Defining a locally in both p() and q() avoids this. They are different variables with the same name, but that name having restricted scope. If p() and q() were parts of a library, then there might be different programmers writing them, which makes it all the more important.
The other case where local variables must be used is in functions which use recursion (including multiple recursion), because here we will have several calls of a function open at the same time in which the same variable will have different values in different calls (but they must not be static, because there is only one copy of a static variable).
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.