473,387 Members | 3,820 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,387 software developers and data experts.

Global Variables

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 you pass the variable in and
then out again... so how is that any different?

Can anyone shed light on these questions?
Jul 19 '05 #1
10 17805
Matt wrote:
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?
Not normally. Only if they arrange to share the same address
space.
I know that you could overwrite a value in a global variable from a
function, but you could also do that if you pass the variable in and
then out again... so how is that any different?


Global variables increase the data coupling of the program
and thus its complexity, because the value can be changed
from anywhere within the program.

Jul 19 '05 #2
"Matt" wrote on 12/11/2003:
Greetings,
What are people's thoughts on global variables in C++?
There's nothing wrong with global variables, but if possible, you
should avoid using them. However, in certain situations they are
necessary. A simple example is when passing a variable through 15
function calls, but only the last function actually makes use of it.
In this case, you're bulking up parameter lists, just to avoid a
global. There are better examples, and hopefully someone else will
give one...
Why are we taught not to use them in programming?
Tracking down faults relating to globals is more difficult than one
restricted to an object or a function. If you find that garbage gets
put into that global, you'll have to watch every access between the
last known good value (which might only be at initialisation), to when
you first see a problem (and that might not actually be the first
occurence of a fault).
Is it true that if you are running two copies of the C program one
copy can overwrite another copies global variable?
No. Global variables are not shared with other programs, full-stop.
It doesn't matter if their the same executable or a different one, a
process' address space is its own. Exceptions can be introduced when
you start with debugging, and such, but that's not what you're asking
(and beyond the scope of this discussion).
I know that you could overwrite a value in a global variable from a
function, but you could also do that if you pass the variable in and
then out again... so how is that any different?
When you say: "pass the variable in and then out again," do you mean
passing a local variable to a function? If so, then what you say is
not necessarily true:

If you pass by value, a copy of the variable is made, so any changes
are not reflected in the original variable.
If you pass by reference, changes are reflected, but you could prevent
that by specifying that the variable is 'const'.
If you pass the address with a pointer, again, changes are reflected
but like references, the memory that the pointer addresses can be
marked 'const'.
Can anyone shed light on these questions?


I hope I did.

Mike

--
Michael Winter
M.Winter@[no-spam]blueyonder.co.uk (remove [no-spam] to reply)
Jul 19 '05 #3
Here's a derived question from your reply :-).

Is there a full proof way to assure than no two copies of the same C / C++
program would ever share the same address space?

Is that the behavior by default and you have to code to share the address
spaec amongst instances of the program? or is it the other way around and
you have to code to assure that the don't share the same address space?

Stéphane Richard
"lilburne" <li******@godzilla.net> wrote in message
news:bo*************@ID-203936.news.uni-berlin.de...
Matt wrote:
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?


Not normally. Only if they arrange to share the same address
space.
I know that you could overwrite a value in a global variable from a
function, but you could also do that if you pass the variable in and
then out again... so how is that any different?


Global variables increase the data coupling of the program
and thus its complexity, because the value can be changed
from anywhere within the program.

Jul 19 '05 #4
Stephane Richard wrote:

Is that the behavior by default and you have to code to share the address
spaec amongst instances of the program? or is it the other way around and
you have to code to assure that the don't share the same address space?


You have to have OS support in order to do it via shared
memory, memory mapped ports, etc, you have to very specific
about it. In general one process will not be able to access
memory owned by another process, at least not on common OS.
Constants may reside in the program's 'text' segment and
could be shared if multiple instances of a program share the
same text.

I wouldn't worry about it. You'll probably never encounter
such things.

Jul 19 '05 #5
ma***@chilitech.net (Matt) writes:
Greetings,
What are people's thoughts on global variables in C++?
Why are we taught not to use them in programming?
Global variables are generally very bad, but occasionally useful where
you want global state. They are used by both the C and C++ standard
libraries for some things e.g. global locale, std::cin, std::cout
etc. are also global objects, albeit within a namespace.

As an example of why it's bad, part of my job involves maintaining
code written in an old DOS-based 4GL database language. It has no
concept of classes or even local variables. Every variable is global.
The result is that each program has around 200 (a few have over 500!)
variable definitions right at the top. This is bad because it's
nearly impossible to keep track of what code uses each variable. Some
hard-to-debug problems are because a variable can be modified in many
places, or used for different purposes.

I'm currently slowly re-writing in C++. For the parts I've rewritten,
the code size has been reduced by a factor of about 10, and I'm
already getting better performance and reliability even though I'm not
finished doing the prototype yet. Another benefit is ease of
maintainence: it took me two weeks solid work to make a trivial change
to the 4GL code, due to the impossible to predict interactions that
made even the smallest change problematic. The same change to the C++
code should take about 20 *minutes*.

C++ or even C are a breath of fresh air after that. The 4GL dogs'
breakfast really makes you appreciate what benefits we derive from
functions and classes. Encapsulating the logic in functions and
classes makes for a much more robust and predictable program. The
code is a joy to write, and looks beautiful.
Is it true that if you are running two copies of the C program one
copy can overwrite another copies global variable?
No, at least for the operating systems I've used (various UNIX,
Windows).
I know that you could overwrite a value in a global variable from a
function, but you could also do that if you pass the variable in and
then out again... so how is that any different?


I'm not sure exactly what you mean here. Could you clarify the
question?
--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
Jul 19 '05 #6
Roger Leigh <${******@invalid.whinlatter.uklinux.net.invalid > wrote in message news:<87************@wrynose.whinlatter.uklinux.ne t>...
ma***@chilitech.net (Matt) writes:
Greetings,
What are people's thoughts on global variables in C++?
Why are we taught not to use them in programming?


Global variables are generally very bad, but occasionally useful where
you want global state. They are used by both the C and C++ standard
libraries for some things e.g. global locale, std::cin, std::cout
etc. are also global objects, albeit within a namespace.

As an example of why it's bad, part of my job involves maintaining
code written in an old DOS-based 4GL database language. It has no
concept of classes or even local variables. Every variable is global.
The result is that each program has around 200 (a few have over 500!)
variable definitions right at the top. This is bad because it's
nearly impossible to keep track of what code uses each variable. Some
hard-to-debug problems are because a variable can be modified in many
places, or used for different purposes.

I'm currently slowly re-writing in C++. For the parts I've rewritten,
the code size has been reduced by a factor of about 10, and I'm
already getting better performance and reliability even though I'm not
finished doing the prototype yet. Another benefit is ease of
maintainence: it took me two weeks solid work to make a trivial change
to the 4GL code, due to the impossible to predict interactions that
made even the smallest change problematic. The same change to the C++
code should take about 20 *minutes*.

C++ or even C are a breath of fresh air after that. The 4GL dogs'
breakfast really makes you appreciate what benefits we derive from
functions and classes. Encapsulating the logic in functions and
classes makes for a much more robust and predictable program. The
code is a joy to write, and looks beautiful.
Is it true that if you are running two copies of the C program one
copy can overwrite another copies global variable?


No, at least for the operating systems I've used (various UNIX,
Windows).
I know that you could overwrite a value in a global variable from a
function, but you could also do that if you pass the variable in and
then out again... so how is that any different?


I'm not sure exactly what you mean here. Could you clarify the
question?


This did help somewhat.. what I mean is.. if the main reason for not
using globals is to prevent accidental change.. then shouldn't I just
be more careful when programming? Couldn't I do just as much damage
passing a variable local into a function and then back out? The only
difference with a global is I messed up coding... but isn't it ALSO
just as bad coding practice to use the same variable locally that is
defined in another function locally? I mean if you use the variable
once you shouldn't use it again, so why not just define it globally
and watch what you do??
Jul 22 '05 #7
Matt wrote:
Roger Leigh <${******@invalid.whinlatter.uklinux.net.invalid > wrote in message news:<87************@wrynose.whinlatter.uklinux.ne t>...
I know that you could overwrite a value in a global variable from a
function, but you could also do that if you pass the variable in and
then out again... so how is that any different?


I'm not sure exactly what you mean here. Could you clarify the
question?

This did help somewhat.. what I mean is.. if the main reason for not
using globals is to prevent accidental change.. then shouldn't I just
be more careful when programming? Couldn't I do just as much damage
passing a variable local into a function and then back out? The only
difference with a global is I messed up coding... but isn't it ALSO
just as bad coding practice to use the same variable locally that is
defined in another function locally? I mean if you use the variable
once you shouldn't use it again, so why not just define it globally
and watch what you do??


By default C++ uses call by value not call by reference,
unless you specify that a parameter is a non-const
reference, or pointer, another function cannot modify the
value of any variable passed to it.

Jul 22 '05 #8


Matt wrote:

This did help somewhat.. what I mean is.. if the main reason for not
using globals is to prevent accidental change.. then shouldn't I just
be more careful when programming?
Lot's of people thought this and all of them came to the same conclusion
eventually:
No. Simply beeing careful doesn't help.

The reason is that programs very quickly cross a 'critical mass'. Once
this critical mass is crossed, the complexity raises that fast, that
it is extremely hard or impossible to recognize all the details.

By using local variables you draw a border. The border limits the scope
of that variable. It is as if you were saying: Your influence region is
up to here but no further.
Couldn't I do just as much damage
passing a variable local into a function and then back out?
No. Cause it you pass something to a function you want to tell the function
something: use this value or calculate and place the result here.
You are using a defined interface and that's ok.

It is like a house: if you don't make any window or doors in your house,
then you don't need to worry of getting robbed. But what good is a house
without a door and/or windows? So you need to lower the security a little
bit in order to make it useful. But this does not mean that you want to
build your house without walls :-)
The only
difference with a global is I messed up coding...
Not really.
but isn't it ALSO
just as bad coding practice to use the same variable locally that is
defined in another function locally?
No, why should it?
Those 2 variables have nothing in common. They just happen to have
the same name, but this isn't a problem, they are still independent of
each other. If you are working on one function, then you are interested in
the details of that function. If there is a local variable called 'count', fine.
Then you switch and are working on another function. There is also a variable called
'count', but since you don't use globals, you know that this is a completely
different variable then the one you previously used in another function.
So you also know (since both are global), that you can change each count
without affecting the operation of the other function. You simply don't care
any longer, that there is another function which uses a local variable 'count'.

I mean if you use the variable
once you shouldn't use it again,
That would be hard to do in real world programs. The system my team is working
on consists of roughly 1 million lines of code, there are at least 60000 up to
100000 (I estimated this numbers, since nobody knows exactly) variables and you
tell me that I shouldn't use a variable called 'count' in more then one function?
If it is a counter and I use it as a counter I will call it 'count' and not worry
about all the other 5000 counter which are used throughout the whole program.
so why not just define it globally
and watch what you do??


Because you can't watch them. At least not when you are writing serious programs
with sizes greater then 50 lines of code.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #9


Karl Heinz Buchegger wrote:
No, why should it?
Those 2 variables have nothing in common. They just happen to have
the same name, but this isn't a problem, they are still independent of
each other. If you are working on one function, then you are interested in
the details of that function. If there is a local variable called 'count', fine.
Then you switch and are working on another function. There is also a variable called
'count', but since you don't use globals, you know that this is a completely
different variable then the one you previously used in another function.
So you also know (since both are global), that you can change each count


must obviously read: ... (since both are local), ...

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #10
Matt wrote:
What are people's thoughts on global variables in C++?
Global *variables* are bad.
Global *constants* are good.
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 copy's global variable?
No.
I know that
you could overwrite a value in a global variable from a function
but you could also do that
if you pass the variable in and then out again...
You shouldn't do that either.
so how is that any different?
Can anyone shed light on these questions?


You should try to avoid using variables.
They only make your code harder for other programmers
to read, understand and maintain.
You will appreciate that when you go back
to modify code that you haven't looked at for six months --
you *will* be that other programmer.

Use constants whenever possible.
You don't need *any* variables to write useful programs.
Place a 'const' qualifier if front of every variable definition
and allow the compiler to *force* you to change it back into a variable.

Don't write functions to pass pointers or references to variables.
Pass by value, const pointer or const reference
and return an object by value instead.
Consider passing a pointer or a reference
*only* for "in-place" operations such as operations
on the elements of a *container* object
like a long list or a large array.

Global constants are good.
Old C programmers used C preprocessor macros to define constants
in header files which could be included in every translation unit.
These macros have become obsolete with the introduction
of the 'const' qualifier.

Global constants, on the other hand, break modularity.
Global constants make the code harder to maintain
because the programmers must consider the impact
of any change of a global variable on every other function
called by the program and, unless they are the original author,
they will be obliged to inspect, analyse and understand
every other function that references the global variable.
Global variables make functions harder to reuse
in other programs because they depend upon other functions
that reference and modify the global
which may have nothing to do with the new program
or that conflict with the new program.

Global variables are *never* necessary.
They may appear to be convenient at first
but they eventually cause problems
which lead new programmers to regret every considering using them.


Jul 22 '05 #11

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

Similar topics

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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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,...

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.