473,545 Members | 1,649 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

To use global variables or no????

Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.

I have a program with a set function that calls 4 other functions in
order - let's say function A, B, C, D.

It always calls function A first which is a function that returns a
system path. Now all other functions require that variable as well
(function A returns a char pointer)

So my question is - should I declare a global variable, set it's value
using function A and then use that variable in the other functions as
well.

Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!

Thanks.

Jun 5 '06 #1
37 2707

eoindeb wrote:
Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.

I have a program with a set function that calls 4 other functions in
order - let's say function A, B, C, D.

It always calls function A first which is a function that returns a
system path. Now all other functions require that variable as well
(function A returns a char pointer)

So my question is - should I declare a global variable, set it's value
using function A and then use that variable in the other functions as
well.

Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!


If I understand correctly, you have one function, say F, that calls
functions A, B, C, and D in order. Function A provides input value for
the other three. I don't see why you should worry about global (file
scope) variables. Just declare a local variable in function F, and use
it to collect return value of A, and pass it to B, C, and D. Such a
variable is not global, although it is used in more functions.

Still, using variables external to the function may not be a good idea,
as looking at the function call it is not immediatelly obvious what are
the inputs, and outputs. You don't have a clean interface, you
introduce (and use) side effects.

As always, global variables do have their uses, but that has to be
judged on a case by case basis. I don't think you provide enough
information about yours to make a good guess.

Jun 5 '06 #2

"eoindeb" <Eo*****@gmail. com> wrote in message
news:11******** *************@u 72g2000cwu.goog legroups.com...
Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.

I have a program with a set function that calls 4 other functions in
order - let's say function A, B, C, D.

It always calls function A first which is a function that returns a
system path. Now all other functions require that variable as well
(function A returns a char pointer)

So my question is - should I declare a global variable, set it's value
using function A and then use that variable in the other functions as
well.

Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!

Thanks.


One problem with global variables is that it is difficult to see where
those variables get changed. For example:

char *str;
int n = 1;

void func1() {
str = (n==1)? "hello" : "bye";
fun2();
fun3();
fun4();
fun5();
/* what are the values of n and str here ? */
The answer to the above question is: i have to examine
the code in fun2, fun3, fun4, and fun5, because I don't know
who might modify the global variables.

If you have a lot of variables that are common to several
of the functions, you can pass them all throught the call,
or you can set up a struct that contains all of the shared
variables, and just pass that struct around.

/* define struct MyStruct */
....

Then:
void func1() {
struct MyStruct s;
/* Fill in initial values */
...
fun2();
fun3(&s);
fun4();
fun5(&s);

Now I know that I only have to examine fun3 and fun5
to find possible changes to the variables.

--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project

Jun 5 '06 #3
eoindeb said:
Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.
First Rule of Global Variables: Don't use them.

Second Rule of Global Variables (for experts only): Don't use them *yet*.
Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!


Parameters.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 5 '06 #4

eoindeb wrote:
Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.

I have a program with a set function that calls 4 other functions in
order - let's say function A, B, C, D.

It always calls function A first which is a function that returns a
system path. Now all other functions require that variable as well
(function A returns a char pointer)

So my question is - should I declare a global variable, set it's value
using function A and then use that variable in the other functions as
well.

Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!


Pass the result of A to B, C, and D as a parameter:

char *path = A();
B(path);
C(path);
D(path);

There are several reasons why you don't want to use a global. First of
all, you won't be able to reuse B, C, or D in another module where that
global isn't defined. Secondly, your code won' t be thread-safe; If
one thread can call A and change the value of the global while another
thread is executing B, C, and D, you'll run into problems. Globals
introduce maintenance headaches; there are few things worse than
finding a bug that's due to two different pieces of code using the same
global for different reasons.

Generally speaking, you want to write your functions so that all the
information they need to do their job is provided in the parameter
list. There are times where you need to preserve state between
function calls (such as the position of a stack pointer in a stack
module), but even that can be written in such a way that the state
information is passed as a parameter, instead of stored in a global.

If you're working in an environment where stack space or register space
is at a premium and the overhead of passing a parameter is causing real
problems, then using a global is justified, but that's a fairly
specialized domain. In those cases, you'll *know* whether using a
global is the right thing to do or not.

Jun 5 '06 #5
On 2006-06-05, Richard Heathfield <in*****@invali d.invalid> wrote:
eoindeb said:
Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.


First Rule of Global Variables: Don't use them.

Second Rule of Global Variables (for experts only): Don't use them *yet*.
Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!


Parameters.

Regarding my earlier posts that seemed to concone global variables:

I wondered why the functions that changed my globals never confused
me; it turned out that I had been habitually passing variables by
parameter, even those that were global.

In conclusion, I moved all my globals to local scope and the code
continued to compile just fine. Lesson learned. There is virtually
never a need for globals.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
If we would just let the poachers into the zoo, we'd
have less squashed people and more fancy pianos!
Jun 5 '06 #6
"Andrew Poelstra" <ap*******@loca lhost.localdoma in> wrote in message
news:slrne892fb .dbo.ap*******@ localhost.local domain...
On 2006-06-05, Richard Heathfield <in*****@invali d.invalid> wrote:
eoindeb said:
Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.


First Rule of Global Variables: Don't use them.

Second Rule of Global Variables (for experts only): Don't use them *yet*.
Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!


Parameters.

Regarding my earlier posts that seemed to concone global variables:

I wondered why the functions that changed my globals never confused
me; it turned out that I had been habitually passing variables by
parameter, even those that were global.

In conclusion, I moved all my globals to local scope and the code
continued to compile just fine. Lesson learned. There is virtually
never a need for globals.


stdin
stdout
stderr
are globals.
Jun 5 '06 #7
On 2006-06-05, Dann Corbit <dc*****@connx. com> wrote:
"Andrew Poelstra" <ap*******@loca lhost.localdoma in> wrote in message
news:slrne892fb .dbo.ap*******@ localhost.local domain...
On 2006-06-05, Richard Heathfield <in*****@invali d.invalid> wrote:
eoindeb said:

Sorry to ask another global variable question, but from reading other
posts I'm still not sure whether to use them or not.

First Rule of Global Variables: Don't use them.

Second Rule of Global Variables (for experts only): Don't use them *yet*.

Or is there a preferred method to achieve what I need? Hope I have made
myself clear!!

Parameters.

Regarding my earlier posts that seemed to concone global variables:

I wondered why the functions that changed my globals never confused
me; it turned out that I had been habitually passing variables by
parameter, even those that were global.

In conclusion, I moved all my globals to local scope and the code
continued to compile just fine. Lesson learned. There is virtually
never a need for globals.


stdin
stdout
stderr
are globals.


Not sure why I have to say this, but I meant /user-defined/ globals.

Also, those aren't necessarily globals. They could be macros or some
other esoteric creature. (Unless the Standard says otherwise. Anyone?)

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
If we would just let the poachers into the zoo, we'd
have less squashed people and more fancy pianos!
Jun 5 '06 #8
Andrew Poelstra said:
Dann Corbit wrote:
Andrew Poelstra wrote:

In conclusion, I moved all my globals to local scope and the code
continued to compile just fine. Lesson learned. There is virtually
never a need for globals.
stdin
stdout
stderr
are globals.


Not sure why I have to say this, but I meant /user-defined/ globals.


It's always best to say what you mean. This is almost certainly Dann's
point. Obviously you're quite new to the group and I don't know very much
about you (e.g. I don't know how old you are, and there's no reason why I
should), but if you're reasonably young it is probably true that Dann has
been writing C programs since before you were born. He knows his stuff.
Listen to Dann. Listen to Dann. He is, so to speak, one of the droids
you're looking for.

Incidentally, the term "global" is very woolly. It's best to refer to the
scope and linkage of objects rather than relying on everyone guessing that
you mean what they mean by "global".
Also, those aren't necessarily globals. They could be macros or some
other esoteric creature. (Unless the Standard says otherwise. Anyone?)


They are expressions of type "pointer to FILE". If they didn't have file
scope and external linkage, they'd be effectively unusable. It is therefore
not unreasonable to call them "globals", since they're about as global as
anything in C gets.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 5 '06 #9
On 2006-06-05, Andrew Poelstra <ap*******@loca lhost.localdoma in> wrote:
In conclusion, I moved all my globals to local scope and the code
continued to compile just fine. Lesson learned. There is virtually
never a need for globals.


You're not an expert yet ;-)

File-scope globals, aka statics, are extremely useful. Think for
instance of a variable with a verbosity level, you don't want to pass
that level everywhere you may want to print a debugging message. Or a
memory manager. In practice, any module which has state but for which
it would become quickly inconvenient to pass struct pointers around
all the time.

Program-level globals tend to be more useful in C++ than C, for
everything that is used a lot and happens to be a singleton. In C++ a
global object is nice, and you hide the functions as class methods.
In C OTOH you make the functions global and hide the state in statics.
I can't imagine cases where a full-on global seems the right method in
C, except for the cases where your module is too big to fit in one
source file.

OG.

Jun 5 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
17836
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 overwrite another copies global variable? I know that you could overwrite a value in a global variable from a function, but you could also do that if...
4
24163
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(); function loadUrlVariables() { varString = location.search;
12
5859
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 these classes. I know there is a pattern called singleton can more or less do such a trick. I am wondering is this the best way to do it (regarding...
2
5173
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 second name for better readable. After optimization, global variables might be misaligned because each global variables must be converted to 32 bits,...
17
5599
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 constantly running tests on imperfect code. On of the cumbersome jobs encountered is reassigning global vars their values after a close encounter with...
33
2993
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 been for years. If the machine has memory to spare and windows can use it - I'm thinking "Why not?" I was wondering what some of you have to say...
9
8626
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 Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the...
5
11802
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 $MYVAR, $a; ?>
1
29318
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 called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this...
112
5368
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 that may print some messages. foo(...) { if (!silent)
0
7393
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7411
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7749
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4942
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3444
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3439
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1871
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
695
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.