473,574 Members | 2,450 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Global variables

Hi all,

I want to know how good or bad it is using global variables i.e
advantages
and disadvantages of using global variables.

Sunil.

Nov 15 '05 #1
13 3063
Sunil wrote:
I want to know how good or bad it is using global variables i.e
advantages and disadvantages of using global variables.


Making variables as local as possible makes it easier to understand their
purpose. Sometimes a program consists of a handful of global objects
though, so it can't be said that they are always necessarily evil.

// consider this bad idea:
int i;
void bar( int xlim)
{
for( i=xlim; i>x/2; --i)
printf("bar(%d) i=%d\n", xlim, i);
}
void foo( int lim)
{
for( i=0; i!=lim; ++i)
bar( i*3);
}

Uli

Nov 15 '05 #2
"Ulrich Eckhardt" <do******@knuut .de> wrote in message
news:3q******** ****@uni-berlin.de...
Sunil wrote:
I want to know how good or bad it is using global variables i.e
advantages and disadvantages of using global variables.


Making variables as local as possible makes it easier to understand their
purpose. Sometimes a program consists of a handful of global objects
though, so it can't be said that they are always necessarily evil.


There's another problem... If you want some function to work in a
multithreaded application (i.e. called from concurrent threads), that
function must not use any global variable but constant. Also, if you want to
use that function in a singlethreaded application but you want to use it
freely from different application parts w/o making them interact, then this
function must not use any global variables too. Any data must be passed to
such functions through a pointer. And the callers pass pointers to different
data to it. That way neither of the above mentioned problems will arise.
That's it.

Alex
Nov 15 '05 #3
Sunil wrote:
Hi all,

I want to know how good or bad it is using global variables i.e
advantages
and disadvantages of using global variables.


Pro: Globally-visible variables increase the "coupling"
between separately compiled modules of a program.

Con: Globally-visible variables increase the "coupling"
between separately compiled modules of a program.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #4
"Alexei A. Frounze" wrote:

"Ulrich Eckhardt" <do******@knuut .de> wrote in message
news:3q******** ****@uni-berlin.de...
Sunil wrote:
I want to know how good or bad it is using global variables i.e
advantages and disadvantages of using global variables.
Making variables as local as possible makes it easier to understand their
purpose. Sometimes a program consists of a handful of global objects
though, so it can't be said that they are always necessarily evil.


There's another problem... If you want some function to work in a
multithreaded application (i.e. called from concurrent threads), that
function must not use any global variable but constant.


Not necessarily. While threads are beyond standard C, any system worth
its salt that supports threads will offer "thread-safe" methods of
accessing global variables.
Also, if you want to
use that function in a singlethreaded application but you want to use it
freely from different application parts w/o making them interact, then this
function must not use any global variables too. Any data must be passed to
such functions through a pointer. And the callers pass pointers to different
data to it. That way neither of the above mentioned problems will arise.


Typically, the reason or making such things global is to allow them to
interact. (That, and "it's not worth the overhead of passing it to every
function". Can you imagine a non-global stdout?)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Nov 15 '05 #5
"Kenneth Brody" <ke******@spamc op.net> wrote in message
news:43******** *******@spamcop .net...
"Alexei A. Frounze" wrote:
There's another problem... If you want some function to work in a
multithreaded application (i.e. called from concurrent threads), that
function must not use any global variable but constant.
Not necessarily. While threads are beyond standard C, any system worth
its salt that supports threads will offer "thread-safe" methods of
accessing global variables.


Right, there are all kinds of critical sections, mutexes, spinlocks,
semaphores, etc.
But that means that at any time only one thread can be executing a function
(or its part) protected thusly, which is not OK everywhere.
Also, if you want to
use that function in a singlethreaded application but you want to use it
freely from different application parts w/o making them interact, then this function must not use any global variables too. Any data must be passed to such functions through a pointer. And the callers pass pointers to different data to it. That way neither of the above mentioned problems will arise.


Typically, the reason or making such things global is to allow them to
interact.


But the interaction isn't always OK. We don't want race conditions, nor we
want something global be damaged by some other component using it at the
same time.
(That, and "it's not worth the overhead of passing it to every
function".
C++ carries that overhead everywhere, but what makes an application bad
isn't this small overhead that scales in a well-defined way, it's the bad
algorithms employed in the application :)
Can you imagine a non-global stdout?)


And while it doesn't necessarily has to be stdout, ability to separate some
input/output during testing and debugging is a good thing. Scaling to more
than one data processing channel needs this too. That's where some kind of
ID comes to play, be it a pointer (to data or function) or an integer
number. For instance, in an embedded system on my hardware I had only one
UART and one ADC/DAC. The code was written in such a way as to scale easily
for more data processing channels than just one which was allowed by my
limited hardware. The customer could develop his own PCB, put more I/O
circuitry to it and do that with this same software. So, who said stdout
ought to be one? There're many! :)

Alex
Nov 15 '05 #6
Alexei A. Frounze wrote:
"Kenneth Brody" <ke******@spamc op.net> wrote in message
news:43******** *******@spamcop .net...
(That, and "it's not worth the overhead of passing it to every
function".


C++ carries that overhead everywhere, but what makes an application bad
isn't this small overhead that scales in a well-defined way, it's the bad
algorithms employed in the application :)


What is this overhead in C++ you are talking about?

Uli
Nov 15 '05 #7
"Ulrich Eckhardt" <do******@knuut .de> wrote in message
news:3q******** ****@uni-berlin.de...
Alexei A. Frounze wrote:
"Kenneth Brody" <ke******@spamc op.net> wrote in message
news:43******** *******@spamcop .net...
(That, and "it's not worth the overhead of passing it to every
function".


C++ carries that overhead everywhere, but what makes an application bad
isn't this small overhead that scales in a well-defined way, it's the bad algorithms employed in the application :)


What is this overhead in C++ you are talking about?


this

Alex
Nov 15 '05 #8

Sunil wrote:
Hi all,

I want to know how good or bad it is using global variables i.e
advantages
and disadvantages of using global variables.

Sunil.


File-scope (global) variables are rarely as useful as they seem, and
should be avoided.

The only reasonable time to use a global variable is when you need to
preserve state between function calls without exposing that information
to the caller. For example, take this simple stack module:

/* stack.c */

#define STACKSIZE 128

/**
* The static keyword is only there to
* prevent these symbols from being exported
* by the linker; the objects have static extent
* by virtue of being declared at file scope.
*/
static size_t stackPointer;
static int stack[STACKSIZE];

void Reset()
{
stackPointer = STACKSIZE;
}

void Push(int value)
{
if (stackPointer > 0)
stack[--stackPointer] = value;
else
/* handle overflow error */
}

int Pop()
{
int val;
if (stackPointer < STACKSIZE)
val = stack[stackPointer++];
else
/* handle underflow error */
}

int Top()
{
return stack[stackPointer];
}

In this example, the stack and stackPointer are used to keep track of
the stack contents between calls to Reset(), Push(), Pop(), and Top(),
and the stack user cannot manipulate these items directly.

This approach has several drawbacks, though. For one thing, you can't
create multiple stacks, since you only have one instance of stack data.
Secondly, and more importantly, it leads to maintenance headaches by
tightly coupling functions; in other words, changing the logic of one
function may have an unintended effect elsewhere if you change how the
global is manipulated. It can also make testing and debugging more
difficult.

If you need to preserve state, but don't want to expose that
information to whoever's using your module, you can hide it behind a
pointer to an incomplete type definition, like so:

/* stack.h */

#ifndef STACK_H
#define STACK_H

/**
* create a pointer to an incomplete type; this way,
* the use of the module can pass the pointer around, but
* cannot access the members of the struct through the pointer.
*/
struct stackData;
typedef struct stackData *stack_t;

/**
* Since the user of the module can only refer to a pointer
* to a stack, we need a way for him or her to create a new
* stack instance. NewStack() will dynamically create an
* instance of struct stackData and return the pointer to it.
*/
stack_t NewStack(size_t stackSize);
void Reset(stack_t stack);
void Push(stack_t stack, int value);
int Pop(stack_t stack);
int Top(stack_t stack);

/**
* Since we're dynamically allocating stacks, we need a way
* to release them as well.
*/
void DestroyStack(st ack_t *stack);

#endif

/* stack.c */

#include <stdlib.h>
#include "stack.h"

/**
* Complete the struct type definition
*/
struct stackData {
size_t stackSize;
size_t stackptr;
int *stack;
} stackData_t;

/**
* Implement the functions, using the stack parameter.
* This is left as an exercise for the reader.
*/

Nov 15 '05 #9
"Alexei A. Frounze" wrote:

"Ulrich Eckhardt" <do******@knuut .de> wrote in message
news:3q******** ****@uni-berlin.de...
Alexei A. Frounze wrote:
"Kenneth Brody" <ke******@spamc op.net> wrote in message
news:43******** *******@spamcop .net...
> (That, and "it's not worth the overhead of passing it to every
> function".

C++ carries that overhead everywhere, but what makes an application bad
isn't this small overhead that scales in a well-defined way, it's the bad algorithms employed in the application :)


What is this overhead in C++ you are talking about?


this


While highly OT for clc, C++'s "this" is only passed to object methods.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 15 '05 #10

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

Similar topics

10
17841
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
24166
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
5175
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
5608
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
3014
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
8627
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
11804
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
29326
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
5386
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
8040
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8225
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7800
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
8092
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...
1
5610
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5296
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
3738
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
3745
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1051
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.