please tell me the best way to declare and define global variables?
5 replies to this topic
#1
Posted 25 July 2010 - 07:22 AM
|
|
|
#2
Posted 25 July 2010 - 07:25 AM
As far as I know, it's best to avoid global variables. But if you must and you're coding in C++ then use const instead of C macros as they are type safe. Also, I suggest you read a bit on heap and stack <here>.
A conclusion is where you got tired of thinking.
#define class struct // All is public.
#3
Posted 25 July 2010 - 07:36 AM
You want to be careful trying to use global variables in C/C++. The file scoping rules could end up biting you when you start writing multi-file programs. The best thing to do is start by thinking about why you even want a global variable. It's often a sign of poor code design.
#4
Posted 25 July 2010 - 08:10 AM
If it's C++ I would recommend that you use class variables instead and implement interface functions to access and work with the variable. I believe that's safer and gives it a more efficient way to work with the global data.
My Code Blog - My Github - Ascension Project - Madness Script Project - Simple-Garbage-Collector Project
There is bound to be something useful somewhere.
There is bound to be something useful somewhere.
#5
Posted 25 July 2010 - 08:54 AM
You might want to read some article about singleton classes.
Singleton pattern - Wikipedia, the free encyclopedia
Singleton pattern - Wikipedia, the free encyclopedia
#6
Posted 25 July 2010 - 09:33 AM
A long long time ago (about 1987) I took over a fairly large C program that made extensive use of global variables. There were 20 or so *.c files an globals were declared in most of the, and used in many of the others. Trying to find out what was declared where was absolutely horrifying. I finally got sick of it and declded to consolidte all those global declarations into one *.c file and declared them all (usng extern keyword) in a header file. What I found was that a few globals were actually declared in more than one *.c file and the C compiler (Lattice C) just silently created duplicate data objects the same name as if they were declared with the static keyword. And that was the cause of several bugs that I was having difficulty finding/correcting.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









