[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 473
  • Last Modified:

Global Variables

Could somebody please settle this debate we're having on global variables. Particularlly where they are stored

http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_21193784.html
0
SaMuEl
Asked:
SaMuEl
  • 5
  • 3
  • 2
  • +3
1 Solution
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi SaMuEl,

Globals in C are pretty straight-forward.

/*  start of program  */

int GlobalVariable;
static int SemiLocalVariable;

int GetSemiLocalVariable ()
{
  int  StackVariable;
  return (SemiLocalVariable);
}

/*  end of program  */


In the text above, GlobalVariable is just that.  It's defined in the GLOBALs block, and defined in such a way that the linker/loader can find it for linking from other modules.  Other modules can access it simply by defining 'extern int GlobalVariable'.

Depending on the environment, SemiLocalVariable is also defined on the GLOBALs block.  The difference is that no global definition is created in the object file so other modules can not link to it.

And, of course, StackVariable is defined on the stack, which is wherever your environment puts it, often at one end of the heap.


Kent

0
 
grg99Commented:
Globals have their good and bad points.

Here are some general guidelines:

In general you should try to minimize the number of globals.  

 If a variable is used in only ONE function, and it doesnt have to keep its value outside of the function, then it should almost certainly be moved INSIDe the function, not as a global.

Also if you're programming without objects, then there's often no other place to put state variables other than in the global namespace.

If you're programming WITH objects, then most globals can go inside your main object.

If you have some variable that is used all over the place, and you don't have an object it can easily be put into, then maybe it should be a global variable.  The alternative is to pass it as a parameter, maybe many many many times and many leves deep.  This can get cumbersome and confusing, not to mention slowing things down.

Sometimes you don't know where a variable is going to be used, in that case I start it out as a global.  But then when the program has "jelled" I take a careful look at each globals, and see if it can be moved inside a function, or into an object.




0
 
PaulCaswellCommented:
I think most of you have it just about right. DeVo seems to have some odd ideas but nothing harmfull (like externs are only allowed in .h files???).

Generally speaking, reducing the number of globals in your code makes for better encapsulation. If you need globals, try to put them together in coherent structure by grouping related ones together into one single global structure.

You can, however, go too far. Too few globals can make your code almost impossible to control. If, for example, you have a program consisting of hundreds of modules which performs a complex process on ten different data files at once, it seem ludicrous to suggest that these files should not be global.

Globals are OK in moderation but making something global just because it is passed as a parameter to abouit ten different routines is NOT a good reason.

You have to walk the line between unmanageable code and stack glut.

Paul
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
TheDevoCommented:
--- QUOTE ---
  int global_distance;
  float global_velocity;
  int global_angle;
Are all truly global variables, that is to say they can be accessed in other c files, much like your public static data members.

If you were to write
static int global_distance;
static float global_velocity;
static int global_angle;
the scope of these variables would be limited to the current c file.

Note that static here, has a completely different meaning to that of static in Java.
--- END QUOTE ---

Assuming that those declairations were made in the same file as your main function:
You could NOT access them in any other file in a multi-file project straight away. Observe:

--- main.c ---
int pointlessGlobalInt;

#include <stdio.h>
#include "myFunction.h"

int main( )
{
      pointlessGlobalInt = 10;
      printf( "Global is %d\n", pointlessGlobalInt );
      myFunction( );
      return 0;
}

--- myFunction.h ---
void myFunction( );

--- myFunction.c ---
#include <stdio.h>
#include "myFunction.h"

void myFunction( )
{
      printf( "Global in another file is %d\n", pointlessGlobalInt );
}
--- End of files ---

If you try to compile those two files into one object, you get:
myFunction.c(6): error C2065: 'pointlessGlobalInt' : undeclared identifier

If you wanted it to work, you would have to add "extern int pointlessGlobalInt;" to either myFunction.c or myFunction.h

[NOTE: I have not used guard conditions to keep the file short. Also, if anyone even thinks about suggesting that you #include "myFunction.c".... well don't.]
0
 
TheDevoCommented:
I think most of you have it just about right. DeVo seems to have some odd ideas but nothing harmfull (like externs are only allowed in .h files???).

Sorry, that was a typo. It should have read in EITHER the .h or .c file ONLY. I was trying to make the point that you don't really need to put them in both :-)

Paul may be right about the need for globals, but so far I haven't found one. I'm currently creating a 2D graphics engine (Coursework), and part of the brief for grade A is that no global variables should be used. If I ever find a situation where global variables are the best solution, I will let you know.
0
 
PaulCaswellCommented:
TheDevo,

I meant no offence. I hope none was taken.

Historically speaking, using no globals used to be called 'functional' programming. Forcing yourself to achieve this is much like fasting. Its a good idea to try it sometimes and, when you do you should do it properly but doing it permanently is not a good idea. I'd actually recommend it to every C programmer to try it on a reasonable sized project at least once. Its a huge eye opener. Its a lot like bug hunting. There IS ALWAYS a way to do it. It is just sometimes a bit mind-boggling.

Paul

0
 
aib_42Commented:
TheDevo, I misunderstood your post at the other thread allright. I am sorry.

PaulCaswell's last post, IMHO, is a nice conclusion about the usage of global variables. I myself use them with caution, like goto, as they tend to make the program prone to errors and much less functional/modular.

Here is the technical conclusion:
Global variables, unless declared with the 'static' keyword, have external linkage, which means that they are "visible" and unique throughout the whole program. However, their scope is limited to the translation units (.c files) they are declared in, so you have to declare them (preferably with the 'extern' keyword where you're declaring them, and without it where you're defining them) in every translation unit you want to be able use them.
0
 
PaulCaswellCommented:
>>...like goto...
Please do NOT interpret my suggestion that Globals are OK in moderation as condoning the use of goto.

THERE IS NEVER ANY GOOD REASON TO USE GOTOS IN C!!!

Paul
0
 
TheDevoCommented:
--- Quote:   kledbetter ---
Anytime anyone ever makes a comment like "xxxx is bad and should NEVER be used", then you should ignore every word they're saying because they're being overdramatic and speaking about something they probably know little about.  Don't you think the folks who designed C and C++ are pretty smart?  Do you think they were sitting around one day, drinking coffee, and one of them says "I know!!  Let's put some STUPID things in our language that are absolutely terrible, and then we'll see if we can trick ignorant programmers into using them!  I know...lessee...a GOTO!  Yea, that's it!  And, how about global variables?  Now that'd be cool!  We'll confuse the hell out of 'em!"
--- End Quote ---

I agree with you Paul, and I'm glad to see more people in this thread following a similar (if less extreme) version of what i've been taughted. However, as the quote above shows, there are always people who do things different ways, for better or for worse.
0
 
PaulCaswellCommented:
And if God had meant us to have showers (s)he would have designed our armpits the other way up.

Paul
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi Paul,

I'm one of those people that avoids GOTO at all costs.  There has never been a GOTO in my C/C++code.

I'm equally againt the setjump/longjump sequence as it generally makes tracking program logic even more obtuse than it already is.  However, I have seen it used and used well.

But GOTO?  Never!


Kent

Give me do/while/for or give me another language!
0
 
aib_42Commented:
>THERE IS NEVER ANY GOOD REASON TO USE GOTOS IN C!!!
...
>But GOTO?  Never!

I will have to disagree. Properly used gotos are no more dirty and unreadable than continue, break statements and premature returns. It is also the way to go, say, when you have 15 levels of nesting of if statements. Duplicating code to have ~96 duplicate statements is one way. Adding 15 extra boolean conditionals is another. Using a well-placed goto target is another. Take your pick, but I am not going to bother reading the code of the first two solutions.
0
 
PaulCaswellCommented:
aib_42, I hope never to have to enhance or support your code.

Paul
0
 
SaMuElAuthor Commented:
Paul, how do you go about breaking out of nested loops without goto?
0
 
SaMuElAuthor Commented:
"GlobalVariable is just that.  It's defined in the GLOBALs block"
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 3
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now