473,467 Members | 1,603 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

What's the best way to define global variable

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 based on your
experiences. any comment or replay will be much appreciated.

David.
Jul 22 '05 #1
12 5849
David WOO wrote:

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.
A singleton surfes a completely different problem.
I am wondering is
this the best way to do it (regarding the convenience and safety),


The best way is to not have the global variables at all.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #2
David WOO wrote:
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 based on your
experiences. any comment or replay will be much appreciated.

David.


Split the global data into categories. Declare a struct to store each
category's data. In your classes, store a const reference to each struct
whose data the class will need to access. The actual objects can be
created in main () and passed to your class constructors. If you think
you might accidentally instantiate any of these structs more than once,
perhaps while you're sleeping, then the singleton pattern is for you;
otherwise I don't think you need to bother with it.

This isn't the best way to design classes, but I hope it helps.

Regards,
Buster.
Jul 22 '05 #3
And with a response like that, we have one less newbie to worry about.

Karl Heinz Buchegger wrote:

David WOO wrote:

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.


A singleton surfes a completely different problem.
I am wondering is
this the best way to do it (regarding the convenience and safety),


The best way is to not have the global variables at all.

--
Karl Heinz Buchegger
kb******@gascad.at

Jul 22 '05 #4
Julie wrote:

And with a response like that, we have one less newbie to worry about.


2 things
* please don't top post. Thank you.
* If you know better then me, then why haven't you provided an answer
on your own?

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #5
"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:40***************@gascad.at...
Julie wrote:

And with a response like that, we have one less newbie to worry about.


2 things
* please don't top post. Thank you.
* If you know better then me, then why haven't you provided an answer
on your own?


When I read this post (quickly, and the first time) I said to myself: "Boy
is Karl getting cranky. There was no need to answer like that."
Then I read it again. After a little thought I said to myself: "Right on.
That is surely a reasonable response to the interchange."

What I think I learned from this is: Without the personal reactions of body
language, facial response, voice tone, etc. just about anything written can
be taken two ways --- as straight and helpful, or as angry and criticizing.
It was the pause and rereading that let me see that my first impulse wasn't
the only, and maybe not even the right, reaction.

Being too lazy to look it up (!) I now ask: does or should the FAQ contain
the advice to read responses that make you angry at least twice with an eye
toward understanding what the response might mean in a more reasonable
light? I'm sure general netiquette FAQ's do.
--
Gary
Jul 22 '05 #6
I don't recall saying that I knew better than you, perhaps you can point it out
to me.

I don't have an answer for the op.

Karl Heinz Buchegger wrote:

Julie wrote:

And with a response like that, we have one less newbie to worry about.


2 things
* please don't top post. Thank you.
* If you know better then me, then why haven't you provided an answer
on your own?

--
Karl Heinz Buchegger
kb******@gascad.at

Jul 22 '05 #7
Julie wrote:
And with a response like that, we have one less newbie to worry about.

Karl Heinz Buchegger wrote:
David WOO wrote:
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.


A singleton surfes a completely different problem.

I am wondering is
this the best way to do it (regarding the convenience and safety),


The best way is to not have the global variables at all.

--
Karl Heinz Buchegger
kb******@gascad.at


Julie,

Karl was not insulting the OP. One of the credos of programming
is to have no global variables. Many programmers work very hard
to eliminate global variables. Global variables a a huge source
of problems in large projects. Encapsulation, data hiding and
Singletons are solutions to the problems imposed by global
variables.

Global variables become very dangerous in multi-tasking and
multiprocessor applications. Search the Web for "mutex",
"resource locking" and "signals" for some techniques.

In some code shops, global variables must go through rigorous
testing. The policing agencies that review the code of asked
"have you tested every piece of code that access the variable
to make sure there are no collisions?" That one takes a lot
of work. After a couple of times of researching and supplying
proof to those questions, one learns not to use globals.

In summary, globals are evil. Most applications can be developed
without any global variables. Those that can't are subject to
rigorous testing.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #8

"Thomas Matthews" <Th****************************@sbcglobal.net> wrote in message news:Jx31c.54374$
Karl was not insulting the OP. One of the credos of programming
is to have no global variables.

Must be one of those fundamentalist religions.

Jul 22 '05 #9
As the original poster of "What's the best way to define global variable", I
thank all of you who contributed to the post. As I started in the beginning
of the first message that I am a newbie, As a matter of fact, I am trying to
understand your personal views, in the meantime, I am trying to find a
solution as well. Buster's response does give me some straight forward
solutions when I solve simple problems, which will likely be used in my
current work. In the meantime, I understand the point of view about "The
best way is not have global variable at all", but it will work in the price
of sacrifying the convenience under some situations. At the moment, I still
can not understand the point put forward by Karl regarding "singleton surfes
a complete different problem", as far as I understnad, the singleton can
functions like a static class in Java, therefore, I works like a global, and
likely it can be a solution to this problem, anyone knows about why it is
not appropriate, could you please give some comments on this.

Thanks again to everyone.

David.
Jul 22 '05 #10
On Mon, 1 Mar 2004 10:24:58 -0000, "David WOO" <ix**@yahoo.com> wrote:
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 based on your
experiences. any comment or replay will be much appreciated.

David.


I my old ways i uses global variables a lot. But to avoid them there a
a lot of strategies to do so.
Look in the book:
"Large Scale C++ Software Design" from Lakos.

Instead of global Variables i would use:

//*.h
class CXX
{
static long aGlobal;
public:
static void SetaGlobla(long a){ aGlobal = a;}
static long GetaGlobal() { return aGlobal;}
};

//*.cpp
long CXX::aGlobal= -1;

///////////////
// use them like this:

CXX::SetaGlobal(7);

long x = CXX::GetaGlobla();
Howie

Jul 22 '05 #11
David WOO wrote:

As the original poster of "What's the best way to define global variable", I
thank all of you who contributed to the post. As I started in the beginning
of the first message that I am a newbie, As a matter of fact, I am trying to
understand your personal views, in the meantime, I am trying to find a
solution as well. Buster's response does give me some straight forward
solutions when I solve simple problems, which will likely be used in my
current work. In the meantime, I understand the point of view about "The
best way is not have global variable at all", but it will work in the price
of sacrifying the convenience under some situations.
That's hard to believe.
Global variables are almost always, and I really believe what I write
here, *almost always*, a source of a problem. You can eliminate them
easily by passing things around, at least that's what function arguments
are for and why they were invented.
At the moment, I still
can not understand the point put forward by Karl regarding "singleton surfes
a complete different problem", as far as I understnad, the singleton can
functions like a static class in Java,


The purpose of a singleton is to make sure, that a specific object
exists only once (or a specific number of times) in your whole system.

The purpose of a singleton is *not* to be a replacement of global variables.
It can be used like that, but by doing so you have gained nothing against
the evilness of global variables. A singleton simply doesn't solve the
problems which make global variables evil, that is: can be accessed and,
more important, changed by any lousy function in your system.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #12
Karl Heinz Buchegger wrote:
Global variables are almost always, and I really believe what I write
here, *almost always*, a source of a problem. You can eliminate them
easily by passing things around, at least that's what function arguments
are for and why they were invented.


I gotta tell you that blanket statements can do much more harm than good.

I wish that we all could get into the habit of justifying statements w/
authoritive sources or real-world experiences.

If you don't have sources to attribute to, say that 'in my opinion' or
'personal experience has shown' and then go off and explain why you feel that
way.

---

In my experience, globals can be the source of problems, bugs, race conditions,
etc. when implemented and used improperly or in a non-standard way without
supporting documentation and pre-meditated design. One of the biggest problems
that I've seen is when globals are used to hold read/write data -- it comes
down to what can/should write to the global, and how are potential readers
notified by the change? A global that changes value a lot, or is nothing more
than a lazy way to get out of passing parameters should definitely be a cause
for concern and a thorough code review.

I've seen and used cases where a global (read-only) variable makes perfect
sense, and is appropriate. For instance, some operating systems have a notion
of a process or instance identifier that is unique for that process. That
identifier is passed into main on program startup, but is otherwise
unavailable. Storing the value of the process id in a global variable can be
justified, but I'd stress that you attempt to guard it from modification by
making access to it read-only. In this case, problems can arise if you
inadvertantly write to it, which can be much easier than it seems if you are
using equality such as if (global_instance = 123) when if (global_instance ==
123) was intended. I'm sure that Karl was speaking of this type of bug which
can be difficult at best to narrow down.

There are numerous authorative resources out there on the subject of globals.
Research and understand the ramifications of global now while you are still
learning as it can be much harder to change bad habits down the road.
Jul 22 '05 #13

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

Similar topics

28
by: David MacQuigg | last post by:
I'm concerned that with all the focus on obj$func binding, &closures, and other not-so-pretty details of Prothon, that we are missing what is really good - the simplification of classes. There are...
4
by: David | last post by:
Hello. I am looking for advice on what is "best practice" regarding looping through a form to check its checkboxes and associated data fields. Here is what I am trying to do (Here is the page...
20
by: Dead RAM | last post by:
Hey people, i'll try to keep this short ;) Here is what I want to type (or at least close too)... #define VER_BUILD 1 #define STR_VER_BUILD "VER_BUILD" But what happends is...
17
by: Woody Splawn | last post by:
I am finding that time after time I have instances where I need to access information in a variable that is public. At the same time, the books I read say that one should not use public variables...
10
by: Jay Wolfe | last post by:
Hello, I'm trying to make sure I use best practices (and hence save myself some headaches) with the declaration and definition of global variables. Let's say I have an app with 30 files,...
5
by: Trev | last post by:
Hi all, Are variables in javascript local to the page, or to the <scripttags they are defined within? Say I had a bit of code as follows: <HEAD> <script> var myVar = MyFunction();
9
by: blangela | last post by:
Can somepoint me to a good discussion on the pros and cons of using #define versus a constant variable in your C+ application? Thanks, Bob
2
by: Tark Siala | last post by:
hi i worked with VB6 then i changed to C#. i want define Variable thats i can accessed from any Form or Class in my project. in VB6 you can do that by define as "Global" in Module, but in C# i...
4
by: Gestorm | last post by:
Hi all, I found a macro "USE_VAR" in the code of bash-3.2 as follows: /*file: bash-3.2/shell.c*/ 344 USE_VAR(argc); 345 USE_VAR(argv); 346 USE_VAR(env); 347 USE_VAR(code); 348 ...
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
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
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...
1
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...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.