473,394 Members | 2,031 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,394 software developers and data experts.

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 3044
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******@spamcop.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******@spamcop.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******@spamcop.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(stack_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******@spamcop.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
Alexei A. Frounze wrote:
"Ulrich Eckhardt" <do******@knuut.de> wrote:
What is this overhead in C++ you are talking about?


this


That's a choice made by the educated programmer whether this overhead is
present in their code.

Uli

Nov 15 '05 #11
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.


I like to use them for profiling.
Then I remove them.

--
pete
Nov 15 '05 #12
If you have information, like a filename, that applies to the entire app and
may be used throughout the program, it should be a global.

In Palm programming, I find file-level globals to be very useful. They help
bring object-orientation to C. They should, however, be used only for that
data that is used by several functions. Note that in Palm programming, you
code functions that respond to messages.

--
---------------------------------------------------------------------
DataGet & PocketLog www.dataget.com
Data Collectors www.baxcode.com
--------------------------------------------------------------------

"Sunil" <su***********@gmail.com> wrote in message
news:11*********************@g47g2000cwa.googlegro ups.com...
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 #13

"John Bode" <jo*******@my-deja.com> wrote

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:

Another case is where you have a huge dataset. For instance in 3d graphics
program you may have hard-coded a list of textures.
Technically you could make your image arrays (probably a few dozen with 64
by 64 24-bit values) local to main, and then pass them down. In practise
they are a lot better in file scope (textures.c), and maybe access functions
to retrieve them by id.
Nov 15 '05 #14

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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...
0
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...

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.