By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,949 Members | 2,043 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,949 IT Pros & Developers. It's quick & easy.

global Variables

P: n/a
Hi newsgroup,

as the subject indicates I am looking for an advice
using global variables. I am not if this problem is more
about style then C. If its wrong in thi group, sorry.

So I have a couple of function that all need the same
information (all located in the same file). By now it looks like

/* file beginns */
static struct sDS discreteState;

void init_discreteState( stuct sDS )
{
/* set the global variable */
}

/* some functions that use the data of the global Variable */

/* file ends */

Is it better to pass the struct every time to the "some functions"
or to make use of a global variable. My teachers often told me that
global variables are not that 'good'. But it seems to save a lot of
passing input from function to an other. Maybe there are other
solution to it?

Thank you,
Michael

Nov 14 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
Michael wrote on 17/12/04 :
So I have a couple of function that all need the same
information (all located in the same file). By now it looks like

/* file beginns */
static struct sDS discreteState;

void init_discreteState( stuct sDS )
{
/* set the global variable */
}

/* some functions that use the data of the global Variable */

/* file ends */

Is it better to pass the struct every time to the "some functions"
or to make use of a global variable. My teachers often told me that global
variables are not that 'good'. But it seems to save a lot of
passing input from function to an other. Maybe there are other
solution to it?


Programmers don't like globals, because

- By-default, there are read/write accessible.
- Anyone that have the name of tha variable and is in scope can read or
write the global. No acess control or tracing is possible
- The attached code works for a unique instance of the data. It make
code not reusable (or you have to double it...loss of sapace and
time... doublons... maintenance becoming harder...

For these reasons, through-pointer accessible data are more
appreciated.

Read more about 'ADT' (Abstract Data Types)

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"

Nov 14 '05 #2

P: n/a
>as the subject indicates I am looking for an advice
using global variables. I am not if this problem is more
about style then C. If its wrong in thi group, sorry.

So I have a couple of function that all need the same
information (all located in the same file). By now it looks like

/* file beginns */
static struct sDS discreteState;

void init_discreteState( stuct sDS )
{
/* set the global variable */
}

/* some functions that use the data of the global Variable */

/* file ends */

Is it better to pass the struct every time to the "some functions"
or to make use of a global variable. My teachers often told me that
global variables are not that 'good'. But it seems to save a lot of
passing input from function to an other. Maybe there are other
solution to it?


When you start having to change a variable, saving the old value,
call one of the functions, and then put the old value back, you'll
start to see a major problem with global variables. It gets even
worse when you have to define a stack of previous values for the
variables. You often start off by assuming that you need one set
of some variables. Often it turns out that you need several, then
an arbitrarily large number of them allocated on the fly.

Passing around input from one function to another, especially
if it's one pointer to a struct, isn't that big a problem, nor should
it be very slow.

Gordon L. Burditt
Nov 14 '05 #3

P: n/a
Michael wrote:
As the subject indicates,
I am looking for an advice [about] using global variables.
Don't.
I am not [sure] if this problem is more about style then C.

I have a couple of functions that all need the same information
(all located in the same file). By now it looks like

// file begins typedef struct sDS sDS; static sDS discreteState;

void init_discreteState(const sDS* p) {
// set the global variable
}

// some functions that use the data of the global variable

// file ends

Is it better to pass the struct every time to the "some functions"?
It is better to pass a *const pointer* every time.
Or to make use of a global variable.
No.
My teachers often told me that global variables are not that 'good'.
You should listen to your teachers.
But it seems to save a lot of passing input from function to an other.
Maybe there are other solution to it?


Ideally, you should pass [large objects] by const reference [pointer]
and return by value. For example

sDS f(const sDS* p);

In particular, you should define a [pseudo] constructor

sDS sDS_create(/* initialization list */);

and a destructor

void sDS_destroy(const *p);

Try to avoid functions that modify objects
but, if you must modify objects,
don't create void functions.
Return a reference [pointer] to the modified object instead:

sDS* modify(sDS* p) {
// modify *p
return p;
}
Nov 14 '05 #4

P: n/a

"Michael" <mi****@gmx.net> wrote

static struct sDS discreteState;

void init_discreteState( stuct sDS )
{
/* set the global variable */
}

Is it better to pass the struct every time to the "some functions"
or to make use of a global variable. My teachers often told me that
global variables are not that 'good'. But it seems to save a lot of
passing input from function to an other. Maybe there are other
solution to it?

You can rapidly get into a mess with global variables. Firstly, all the
functions become dependent on the global, and secondly there is a
psychological issue - it is much easier to document a function's use of
parameters than its use of globals, becuase the caller has to type in the
partameters when he calls the function.

On the other hand if you pass a structure called "myglobals" to every single
function in the program, you have effectively defeated the point of having
encapsulation.

I have found that there are a few situations where in practise it is better
to use a global. One is where you have input or output devices that are
shared. C's stdout, stdin, and stderr are examples of this. Another example
would be a global HINSTANCE in a windows program or connection to the X
server under UNIX.
Another situation is where you need to use a function pointer. For instance
if you want to measure the number of comparisons performed by qsort, it is a
lot easier simply to use a global than to try to hang the data off the
elements.

A similar situation can apply in recursive functions. Usually the overhead
of passing an extra parameter can be ignored, but recursion is the exception
to this rule.
Another situation occurs quite frequently in games, where you have a
"world". The "world" needs to be accessed by many functions. For instance
the collision routine needs the world, and higher-level game logical needs
to check for collisions. It is sometimes possible to write the thing so that
everything takes a "world" as a parameter, but you find that you are
constantly changing and updating the world structure. Often a judicious use
of globals is better.

So globals are generally a bad thing, but sometimes the best solution.
Nov 14 '05 #5

P: n/a
Hi,
and thank you all, for taking the
time to answer my question. The
answers help me a lot.

have a nice christmas time

Michael

Nov 14 '05 #6

P: n/a
Michael <mi****@gmx.net> wrote:
/* file beginns */
static struct sDS discreteState;

void init_discreteState( stuct sDS )
{
/* set the global variable */
}

/* some functions that use the data of the global Variable */

/* file ends */

Is it better to pass the struct every time to the "some functions"
or to make use of a global variable. My teachers often told me that
global variables are not that 'good'. But it seems to save a lot of
passing input from function to an other.


Depends. If it really _is_ a global variable (i.e., if there's only one
of it, and most if not all functions need to use that one variable
(think user preferences, for example)), then it should be global. This
situation isn't quite as common as beginning (and all too many no longer
beginning) programmers often think, though, which is why globals have a
deserved reputation for making code hard to maintain.
If there are a handful of functions spread throughout the program which
use this variable, just pass it around. It doesn't have as much of an
impact as you'd think, especially with modern, optimising compilers.

There's a third possibility, but it may not apply to your situation. If
you have a variable which needs to be shared by several functions which
belong together, then it could be useful to put all those functions in a
single source file (which, in that case, they may very well be already),
and make the variable a static at file scope. This makes it global to
that source file only, and it cannot be accessed from outside that
source file unless you pass a pointer to it from the inside. A good
example for this would be the seed value of a random number generator,
which needs to be used by both the random number function and the
seeding function.
This only works if you don't need an unspecified number of that kind of
variable. For example, it is tempting to use this for binary tree
functions, putting all tree functions in one file and making the root of
the tree a static at file scope in that file - but that makes it much
harder to have two trees in your program.

Richard
Nov 14 '05 #7

P: n/a
On Fri, 17 Dec 2004 13:39:30 UTC, Michael <mi****@gmx.net> wrote:
Hi newsgroup,

as the subject indicates I am looking for an advice
using global variables. I am not if this problem is more
about style then C. If its wrong in thi group, sorry.


I'm now programming for more than 20 years not only in C: There are
something that speaks against od using global variable:

- globals are visible outside its intent.
- globals can be changed anywhere in the module
or if defined as extern in the whole program
- it makes the maintenance not even easy
- it makes it sometimes quite impossible to conrol acces
- it make the whole program non-transparent

But there are some arguments speaking for globals:
- saves tracking parameters through hierarchies of function calls
- it can save lots of runtime because mostenly calling
parameterless functions are done more quickly

In practice you would design your program carefully and define
variabels

- used in each and any corner of the application globally on
a central point. This is on one and only one source module.
This would be the module hosting main() or a data only one.
- as you would design your program modular, meaning that
objects (in thinking objectoriented) have each theyr own
source module or a hierarchy of source modules you would place
them in the top level - if they have to be accessible
to all modules or as static in the only module you needs them.
- you would even be thrifty in creating them.

But you would try in any way to define variables inside functions
whenever possible and give them as parameters to more global designed
funtions.

It makes no sense to give variables to functions only to give them to
functions that gives them to functions that gives them to functions to
been used here and only here whereas they are never used in higher
functions other than to pass them to functions.

So build a clean leveled structure:

- the module hosting main()
- define all variables used really over the whole application
declare them in a header file that will be included in
any translation untit that needs to know of them
- define all variables inside the module but shared by
multiple functions located inside the same file.
You saves the work to think about all and any variable that
is needed in all/many objects.
- modules that hosts an object, even as you would have multiple
translation units to handle the whole object.
This module will hold all the external interfaces to
other sections of the program, but no lower level function.
- defined as extern anything that is used by more than one
translation object
- define as static in file level all variables need by
multiple functions inside the same translation object
- define as static on function level variables used only
inside a specific function.
- build a header file containing all the declarations
needed to know by more than one translation module but
not by the whole program
- modules hosting the specific function group of an object
- same as above.
- lover levels: same as above.

Encapsulating variables as possible helps you to code errorfree.
Encapsulation functions in the same technics helps you too.

It is essential to place variables on the right place. Sometimes it
can help to write simple access methods to get the content of a
variable you have no reguar access to - but needs it value.

As C is not a object oriented language you have no service from the
language to write object oriented code - but there is nothing that
hinders you to thing the object oriented way and structure your code
and variables in that way.

Global variables helps you to get your work done without overloading
any function with more parameters as you absolutely needs to supply to
them to profit from theyr work. That means you would not have to think
about the parameters a function needs that gets called from the
fuction that gets called from the function ... you calls in the
function you needs a piece of work done.

You would plan actual parameters that changes its values on each call
but are unchanged for longer as the current run through the calling
hierarchy.

True, it is hard to find the right location for a variable that gets
used on different places - but it is worth to make this design right
even bevore the code gets written.

The same as above is guilty for functions themselfs. Make them visible
to outside a translation unit only if and only if direct access to
them is really needed from outside.

The right structure of header files helps you handle the visibility
outside of a single translation unit too.

Let a header file #include all headers it needs to bring any data and
function declaration into visibility it needs - but only that.

Plan the interfaces (global data and function declarations) carefully
and test the plan more carefully before you tries to write the first
real statement! Yes this job is quite more hard than to hack
statements into the keyboard - but you will be repayed by significat
shorter coding and testing phases.

You should write a book containing the whole design, the whole
interfaces to document the application. Sure, you would not publish
that book but it will document each detail of all the jobs the
application has to do. It will document the whole structure of your
application, each detail what it has to do, each detail how it is done
- without any programming statement.

You will start up with a rought description. That description will
fall into more and more details giving you at least a fine plan of
- variables needed
- locations of the variables
- startvalues needed
- prototypes of functions
- locations of the fuctions

You'll find helper functions to save multiple writing of the same
function or similar ones. Writing that all in plain english is more
easy and better understundable than coding in a programming language.

Check that all and recheck following the logical pathes an action
would run through to be sure that each action would do exactly what
you want that it has to do. Repair errors at that point. Review it
again. That means check if any variable you needs is visible, that
they have the right value at the right point, that each prototype
fullyfies its needs.

Anything that you does until here will save you month of debugging.

Lay down that book beside your keyboard and start coding the header
files. Go through the headers, checking tat any action will follow its
pathes they have to do. Start up and write the lowest level
translation module. Write a debug main() and debug this module
carefully with any possible lowest and highest values in the variables
the functions can get, do the same with invalid values. As all headers
are complete you can #include them. You can prepare the debug main()
to setup all data and debug anything.

You can write the debug main() in an own module to have it out of the
source tree but you may even encapsulate it with the preprocessor so
that it will not get transated when you compiles it for later binding
into your program.
When it is working perfectly then write the next module on that level
.....

The last you would do is to write the real main. Anything lower than
that is tested, so you have only to test the main itself and follow
down into lower level modules only when the debugging of main shows an
unwanted behavior that is not clearly inside the main module.
--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Nov 14 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.