473,766 Members | 2,093 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is it that bad to initialize global variables at outside?

vib
Hi there,

By chance, I came to learn that it is bad programming practice to
initialize global variables at outside of programs. Is it that bad? In
order to fullfil this, I had to declare them with const, but thereafter
they are no longer variables. Just couldn't see the benefits of this
practice. Any comments or advices are welcome.

Thanks
vib

Nov 14 '05 #1
18 8648
On 6 Jun 2005 06:14:04 -0700, "vib" <vi*****@gmail. com> wrote:
Hi there,

By chance, I came to learn that it is bad programming practice to
initialize global variables at outside of programs. Is it that bad? In
order to fullfil this, I had to declare them with const, but thereafter
they are no longer variables. Just couldn't see the benefits of this
practice. Any comments or advices are welcome.


Global const variables are, indeed, of very little use. If you need
some constant value that can be used in your program then you should
use a #define or enum.

The book "Code Complete" (McConnel, now in its 2nd edition) lists
reasons to avoid global variables and some reasons in which they can
be handy. In general, they should be avoided if there is an
alternative.

Nov 14 '05 #2
"vib" <vi*****@gmail. com> writes:
By chance, I came to learn that it is bad programming practice to
initialize global variables at outside of programs. Is it that bad? In
order to fullfil this, I had to declare them with const, but thereafter
they are no longer variables. Just couldn't see the benefits of this
practice. Any comments or advices are welcome.


Initializing them or not isn't really the issue. Global variables
themselves can cause problems. For example, if a function
communicates only with its caller, and only via its parameters and
return value, it's relatively easy to analyze what it does. If it
also uses global variables, it can affect, and be affected by, any
other functions that use the same global variables, even in the
absence of an explicit call. The graph of dependencies among the
various functions in your program, which would otherwise have been a
simple tree structure, becomes a bowl of spaghetti.

If you need to use global variables, go ahead and use them (just be
careful). And if you're going to declare a global variable, it
usually makes sense to initialize it, just like any other variable.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #3
On Mon, 06 Jun 2005 15:36:05 +0200, Paul Mesken wrote:
On 6 Jun 2005 06:14:04 -0700, "vib" <vi*****@gmail. com> wrote:
Hi there,

By chance, I came to learn that it is bad programming practice to
initialize global variables at outside of programs. Is it that bad? In
order to fullfil this, I had to declare them with const, but thereafter
they are no longer variables. Just couldn't see the benefits of this
practice. Any comments or advices are welcome.
Global const variables are, indeed, of very little use.


They can provide information for the rest of the program.
If you need
some constant value that can be used in your program then you should
use a #define or enum.


These are simpler in a lot of cases, but other than that I don't see a
strong reason to use them in preference.
The book "Code Complete" (McConnel, now in its 2nd edition) lists

reasons to avoid global variables and some reasons in which they can
be handy. In general, they should be avoided if there is an
alternative.


The problems with global variables are much reduced if they are const.
many people would say that macros are pretty nasty, a very blunt tool
sweeping over issues of scope, namespace etc. Just because there may be an
alternative to global variables doesn't mean it is a better one.

A reasonable use of global variables can be a write once or in one place,
read anywhere approach e.g. for config data. It is a pity that C doesn't
provide an easy way to enforce this.

Lawrence
Nov 14 '05 #4
On Tue, 07 Jun 2005 11:20:11 +0100, Lawrence Kirby
<lk****@netacti ve.co.uk> wrote:
On Mon, 06 Jun 2005 15:36:05 +0200, Paul Mesken wrote:
If you need
some constant value that can be used in your program then you should
use a #define or enum.


These are simpler in a lot of cases, but other than that I don't see a
strong reason to use them in preference.


One of the reasons I could think of is that an attempt to modify a
const object (indirectly) results in undefined behaviour, which may
very well turn out to be that the const object is simply modified as
if it didn't have the qualifier "const" at all. Such things have the
danger of turning into programming habits.

Also, a const is not a "constant expression" so its use is a bit more
limited in this respect (its value cannot be used in compile time).

All in all, I think that the "global const vs. #define" debate is a
bit like the "goto debate". There might be cases in which global
consts are prefered but, I suspect, not many :-)

Nov 14 '05 #5
Lawrence Kirby wrote:
.... snip ...
A reasonable use of global variables can be a write once or in one
place, read anywhere approach e.g. for config data. It is a pity
that C doesn't provide an easy way to enforce this.


Something I have been known to do:

const stuffT *thingummy(void )
{
static stuffT *data;

if (!data) {
/* code to malloc and initialize data */
}
return data;
}

Adjust nomenclature to suit.

--
Some useful references about C:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
<http://www.dinkumware. com/refxc.html> (C-library}
<http://gcc.gnu.org/onlinedocs/> (GNU docs)
Nov 14 '05 #6
Lawrence Kirby <lk****@netacti ve.co.uk> writes:
A reasonable use of global variables can be a write once or in one place,
read anywhere approach e.g. for config data. It is a pity that C doesn't
provide an easy way to enforce this.


A reasonable alternative can be a function that initializes a
piece of data on its first call and returns the data or its
address on every call.
--
"Give me a couple of years and a large research grant,
and I'll give you a receipt." --Richard Heathfield
Nov 14 '05 #7
vib
>
const stuffT *thingummy(void )
{
static stuffT *data;

if (!data) {
/* code to malloc and initialize data */
}
return data;
}

Adjust nomenclature to suit.

I think the contents of stuffT is still changable,
let say,

typedef struct {
unsigned int myInt;
} stuffT;

main()
{
const stuffT *pMyData;
stuffT newData;

pMyData = thingummy();

newData.myInt = 10;
pMyData = (stuffT *)&newData;

...
}

Nov 14 '05 #8
CBFalconer wrote:
Lawrence Kirby wrote:

... snip ...

A reasonable use of global variables can be a write once or in one
place, read anywhere approach e.g. for config data. It is a pity
that C doesn't provide an easy way to enforce this.


Something I have been known to do:

const stuffT *thingummy(void )
{
static stuffT *data;

if (!data) {
/* code to malloc and initialize data */
}
return data;
}

Adjust nomenclature to suit.


Another possibility is to store configuration data in a hash.
The hash can be initialized in the c file controlling config, elsewhere
the function to read from the hash is the only one exported.

This is also useful because the config file can be in the format "key .
value", making it possible to add new parameters without changing too
much code.

Nov 14 '05 #9
vib wrote:
const stuffT *thingummy(void )
{
static stuffT *data;

if (!data) {
/* code to malloc and initialize data */
}
return data;
}

Adjust nomenclature to suit.


I think the contents of stuffT is still changable,


Please don't strip attributions of material you quote.

stuffT is a type above, not a variable. thingummy returns a
pointer to an initialized and unalterable instance of the type, and
the initialization etc. is done with code in thingummy. Nothing
except that code can get at it barring suspicious constructs (which
includes extraneous casts).
--
Some useful references about C:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
<http://www.dinkumware. com/refxc.html> (C-library}
<http://gcc.gnu.org/onlinedocs/> (GNU docs)
Nov 14 '05 #10

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

Similar topics

2
8277
by: WhyteWolf | last post by:
I'm trying to set a object as global for access through out the rest of my script ... {a basic SQL accessing object} however if I try calling the object from with in another object it acts as if it isn't global and hasn't been accessed at all ... weather I decalre it from inside the object or declare it outside the object I would rather not have to resort to the standard of refrenceing sence I plan on having modular support and having this...
4
2196
by: MackS | last post by:
Hi I'm new to Python, I've read the FAQ but still can't get the following simple example working: # file main_mod.py: global_string = 'abc' def main():
9
2378
by: Tony Johansson | last post by:
Hello! I know it's bad design to use global variables. I just want to ask a question about them. Is global variables and global static variables the same. These are define outside any function at the top of the a file where you have them. //Tony
22
5471
by: inigo.villalba | last post by:
Hi, I hope someone can point out my error because I'm starting to lose my hair over this. It's probably a very straigh forward error but after only 4 hours sleep it's doing my head in. It's to do with global variables in Firefox 1. The following code works no problems and generates a whole bunch of numbers <script type="text/javascript">
38
2778
by: Lasse Vågsæther Karlsen | last post by:
After working through a fair number of the challenges at www.mathschallenge.net, I noticed that some long-running functions can be helped *a lot* by caching their function results and retrieving from cache instead of calculating again. This means that often I can use a natural recursive implementation instead of unwinding the recursive calls to avoid big exponential running-times. Ok, so I thought, how about creating a decorator that...
5
3581
by: george r smith | last post by:
In the MSDN documentation there is a reference to "the global scope". For example "You can declare types directly in the global scope." I have search extensively and can not find a definition of the "global scope" but could it be the space above the namespace reserved word, such as: public class Bank { ... } namespace Banking
8
1297
by: mb | last post by:
1) you can't declare anything outside of a class, enum, etc. Thus you can't declare globals right after the namespace declaration. I just don't understand why Microsoft decided to do away with easy to use/declare/understand global variables. Even C++ can do this. I used to put globals all in one spot for easy maintaining, this is intuitive. Now they are spread all over the code, in different classes as "static" variables, which to...
3
2000
by: ojorus | last post by:
Hi! Just two short questions..: 1) In a function I want to get the value of a global variable declared outside the function. Should I use "global $variable" or $GLOBALS? Are there any differences in performance or other aspects which should make me choose the one thing or the other? 2) Generally, is it better to pass arguments to the function instead?
3
5616
by: sunbeam | last post by:
Short Description of the Project: we developed a e-learning system for our students. each student has a unique username/password to view the modules he/she should view and nothing more. since we want to give them the opportunity to run these modules from home as well, we are trying to get the USERNAME/COMPUTERNAME as well, so the students, when they sign up for the modules, they can ONLY run the modules fromhome PC. We found a nice...
0
9568
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
10168
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
10008
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
9959
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,...
1
7381
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
5279
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
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 we have to send another system
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.