473,385 Members | 1,925 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

global Variables

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
7 3093
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
>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
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

"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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Matt | last post by:
Greetings, What are people's thoughts on global variables in C++? Why are we taught not to use them in programming? Is it true that if you are running two copies of the C program one copy can...
4
by: Andrew V. Romero | last post by:
I have been working on a function which makes it easier for me to pull variables from the URL. So far I have: <script language="JavaScript"> var variablesInUrl; var vArray = new Array(); ...
12
by: David WOO | last post by:
Hi, I am a newbie on C++, I need to define some global variables which should be accessible to most classes. In the mean time, I don't won't the global variables be modified freely at most of...
2
by: Bryan Parkoff | last post by:
….I would like to know which is the best optimization to use global variable or global struct. I always tell C/C++ Compiler to turn on optimization. ….I use underscore between first name and...
17
by: MLH | last post by:
A97 Topic: If there is a way to preserve the values assigned to global variables when an untrapped runtime error occurs? I don't think there is, but I thought I'd ask. During development, I'm...
33
by: MLH | last post by:
I've read some posts indicating that having tons of GV's in an Access app is a bad idea. Personally, I love GVs and I use them (possibly abuse them) all the time for everything imaginable - have...
9
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang...
5
by: Sandman | last post by:
I dont think I understand them. I've read the section on scope in the manual inside out. I'm running PHP 5.2.0 Here is the code I'm working on: //include_me.php <?php $MYVAR = array(); global...
1
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have...
112
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.