By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,959 Members | 1,196 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,959 IT Pros & Developers. It's quick & easy.

Global Variables

P: n/a
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
Share this Question
Share on Google+
10 Replies


P: n/a
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

P: n/a
"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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a


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

P: n/a


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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.