473,782 Members | 2,623 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 17881
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.u k (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******@godzi lla.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 <${******@inval id.whinlatter.u klinux.net.inva lid> wrote in message news:<87******* *****@wrynose.w hinlatter.uklin ux.net>...
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 <${******@inval id.whinlatter.u klinux.net.inva lid> wrote in message news:<87******* *****@wrynose.w hinlatter.uklin ux.net>...
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

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

Similar topics

4
24185
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
5883
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 the convenience and safety), as this is such a fundamental thing, I believe most of you have a say...
2
5189
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, but I do see that C/C++ Compiler do padding between variables. Struct does the same to do padding....
17
5631
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 an untrapped runtime error. Rather than writing a procedure to simply reassign them all with a...
33
3051
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 about that, particularly any severe "gotchas" you've had the unfortunate experience to contend with.
9
8659
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 following: '-----Begin module code
5
11829
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
29382
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 condition. The opinions expressed in this article are those of the author alone although many have...
112
5480
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
9639
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9474
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10308
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10143
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10076
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9939
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7486
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5507
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.