I am storing the positions of players for a program i am writing to arrays stored as global variables, an example of which is:
float motor1[] = {4.312, 27.312};
Any time a move is made, I have functions called checkposition, move player and update position that retrieve and update this array. All of these functions are in one module called motor.c and have a hierarchy in which they are performed. I have a main module main.c which calls on this module and passes it some information and the motor.c processes it and then spits out an answer. The thing that confuses me is that since the array is saved as a global variable does that mean that it is initialized every time this module is called? Which would mean that my update position function would never work beyond the first move.
No, if it's a global variable, it gets initialized just once, on program startup.
No, a global variable is initialized when the program start up (and only then)
Related
I'm assuming no but not positive. Not sure If other variables can take up the same spot in the stack.
No. A function's local variables are not always at the same address.
Consider a recursive function. If the local variables were supposed to be in the same place, all their values would have to be copied in and out each time you went in and out of recursion.
The normal way of doing it is that each function call has a "block" on the stack. If you call the same function twice in a row the local variable addresses will probably be the same. If you call it recursively the second call will be in a different area of stack and so the local variable addresses will be different.
The compiler will generate code to assign memory addresses based on a "stack pointer" address + offset. So, the actual physical address for each local will vary on each invocation of the function. The offset may well be the same each time because the compiler code gen logic will be the same. The stack pointer address is likely to be different based on what else gets executed before the next invocation of the function.
I've actually seen some results by testing it, but I want to know which way is better and why.
Question #1: Do local variables get declared every time when I call that function again and again? I know that it is better to declare variables in the narrowest scope possible. But I can not stop myself thinking about declaring it as a global variable and make it get declared only once, not in every function call. Or, does it get declared again in every function call? I know that the scope of a local variable is only that function. So when it leaves that function, it must forget that variable as it is going out of its scope right?
Question #2: When I have some function variables which need to store its previous content(e.g. timer counter variables), which way is better: to declare them as a global variable or to declare them as a static local variable? I don't need them to get their initial values whenever I call that function, I am already setting them to zero or etc whenever I need.
Question #1: Do local variables get declared every time when I call that function again and again?
A1: Yes, but it's not an issue really.
Declaring a local variable means that space is made for that variable on the stack, within the stack frame of that function. Declaring a variable global means that space is made for that variable in the data section of the executable (if the variable is initialized), or the BSS section (if not).
Allocating on the stack comes at zero cost. At function entry, the stack frame is sized to make room for all local variables of the function. One more or less does not matter. Statically allocating (for a global variable) is a tad quicker, but you only get that one variable. This can become a huge issue at some later point, e.g. if you want to make your program multithreaded, your function re-entrant, or your algorithm recursive. It can also become a major hassle during debugging, wasting hours of unproductive time while you are hunting down that bug.
(This is the main point of it all: The performance difference is really negligible. The time you can waste on a suboptimal design riddled with globals, on the other hand, can be quite significant.)
Question #2: [...] which way is better: to declare them as a global variable or to declare them as a static local variable?
A2: From an architectural standpoint, avoid globals wherever possible. There are a few specific cases where they make sense, but you know them when you see them. If you can make it work without globals, avoid them. (The same is true, actually, for static locals. They are better than globals as they are limited in scope, and there are cases where they make sense, but local variables should really be the "default" in your mind.)
Global variable - declared at the start of the program, their global scope means they can be used in any procedure or subroutine in
the program
It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.
Local variable - declared within subroutines or programming blocks, their local scope means they can only be used within the
subroutine or program block they were declared in
Local variables are initiated within a limited scope, this means they are declared when a function or subroutine is called, and once the function ends, the memory taken up by the variable is released. This contrasts with global variables which do not release memory.
Question #1: YES. Local variables get declared every time when you call that function again and again. After it leaves the function it forgots the variables that you declared in that scope. You must also remember that when some variable faced, the program will start to search for it. So when it is closer like declaring in the same scope, it will find faster and be able to continue. Also this will be more efficent while you are coding and will cause less bugs and mistakes etc.
Question #2: If you use the same variable with different functions, I strongly suggest you to declare them as global or define, this will lead the program to carry your "counter" with it. So it can be fastly use it when you need between the scopes you travel.
But after these conditions I must strongly suggest you to:
avoid globals wherever possible (as #DevSolar said)
Q2:
It is usually more preferable to use static variables in your function. The main reason is that since all functions can access global variables, it is very hard to keep track of and debug your program.
Q1:
Yes, local variables are created every time the function it belongs to is run, and deleted when the ends.
Suppose your program has 5 functions (that are rarely used), and each function uses 6 local variables. If you change them all to global variables, you will have all 30 variables taking up space for the entire duration of your program, instead of only have 5 variables occasionally being created and destroyed. Moreover, allocation does not really take much time.
I'm alarmed to see that a newly declared array is being contiminated with some random values and some partial values from other variables within my C program.
Here's the source code of my function. I'm basically writing some pseudo code in preparation for doing some complex XML parsing and file manipulation (think similar to a mail merge). Anyway I'm concerned if there are random values in my newly declared array. Why isn't it empty of values when I first declare it?
Do I really need to traverse my entire array to set it's elements to blank values before I begin assigning values or is it likely that there's something wrong with other variable declarations in my code?
Thank you for your help.
Regards,
Chris
void ShowArray(void)
{
char aryString[5][5][255];
sprintf(aryString[1][1],"AAAAA");
sprintf(aryString[1][2],"BBBBB");
sprintf(aryString[1][3],"CCCCC");
sprintf(aryString[1][4],"DDDDD");
sprintf(aryString[1][5],"EEEEE");
sprintf(aryString[2][1],"A2");
sprintf(aryString[2][2],"B2");
int numRow;
int numCol;
for (numRow=1;numRow < 6;numRow++)
{
for (numCol=1;numCol < 6;numCol++)
printf("%d,%d:%s\n", numRow, numCol,aryString[numRow][numCol]);
}
}
Unfortunately you have to initialise the values of every element in an array.
Having random values populating your array and variables when you first declare it is normal. This is because when your computer frees up memory, it doesn't reset them to zero. You computer just allows other programs to overwrite the values in those newly freed memory locations.
Those uninitiallized values are just leftovers from other functions.
A local variable in a function will have an initially undefined value. This is, in fact, what you want, since the alternative would be for the compiler to force an initialization that in most case you don't want, unavoidably slowing your function. It is your responsibility to ensure that any variable has been properly defined before trying to use its value. I have never found this to be a problem.
You are also writing to the [1][5]th string in your code with sprintf. Your aryString variable is of dimensions [5][5][255]. Remember that array indexing in C is 0-based. You should not go beyond the [1][4]th element. You might want to delete that line and try again, because you will end up corrupting your own data by yourself.
Yes, all auto(opposite to static, which is declared explicitly) variables you declare in a function calls for manual initialization. The compiler won't initialize it automatically because it don't know what do you want to be written to that memory. To make it write the default value, which is usually 00000000, to uninitialized variables, write char aryString[5][5][255] = {};, or more commonly, char aryString[5][5][255] = {0};.
Also, the value an uninitialized variable contains is not only a garbage value, but also likely a trap representation, and merely accessing it will cause undefined behavior.
If I understand right that global variables (which go into data segment) in C are initialized where auto variables (which go into stack) are not. or perhaps the other way round?
Why is it so? What is merit of compiler not initializing both kind of variables? Does it increase speed etc?
As you say, global variables go in the data segment, so their value is contained in the final executable, and it might as well be an initialised value as there is no performance difference either way.
On the other hand, local variables are allocated onto the stack, which is set up at run time, so initialising them would have a performance hit.
You understand right, global are initialized, auto are not. This is because globals are loaded directly from the program binary image and the initialization is "free", whereas auto are on stack, and code needs to run to change values and initialize them (i.e.: performance hit).
I'm reading The C Book to try and get a better foundation in C. While I think I'm generally getting the concept of pointers, one thing sticks out to me is that it seems like it's generalizing whatever it's pointing to into a global variable (e.g. the ability to use pointers to return values from void functions), which naturally carries with it all the attendant dangers, I assume.
Aside from the fact that a pointer references a specific variable or index in an array, what is the difference between a pointer and a global variable?
They're quite different beasts. To better explain, let me define both.
Pointers:
A variable holds some piece of data. A pointer is a type of data that refers to another piece of memory. Think of it as a sign that says "Over there ---->" pointing at an object of some sort. For example, strings in C are just a pointer to a character, and by convention, you know there's more characters following it until a \0 character. C uses pointers extensively, since there's no other mechanism for sharing common information between parts of the program, except for....
Global Variables:
In a program, you have variables in each function. These can be the parameters to the function, and ones defined inside. As well, you have what are known as global variables. These variables store information that all the functions in a file can access. This can be useful to pass things like a global state around, or configuration. For example, you might have one called debug that your code checks before printing some messages, or to store a global state object, like the score in a video game.
What I think is confusing you: Both can be used to share information between parts of code. Because function arguments are passed by value in C, a function can't modify the variables of what calls it. There are two ways to "fix" that problem. The first (and correct) way is to pass a pointer to the variable into the function. That way, the function knows where to modify the parent's variable.
Another approach is to just use a global variable. That way, instead of passing around pointers, they just edit the global variables directly.
So you can use both of them to accomplish the same thing, but how they work is quite seperate. In fact, a global variable can be a pointer.
A global variable is any variable that is accessible in any scope. A pointer is a variable that contains the address where something lives.
They aren't directly related to each other in any way.
A pointer variable can be in global or local scope and can also point to a variable that is in global, local, or no scope (as if it were coming off of the heap or addressing some DIO lines).
There's a huge difference. Aside from the "other" uses of pointers (which include dealing with strings and arrays, and building dynamic data structures like trees and linked lists), using a pointer to give another function access to a local variable is much more flexible and controlled than sharing a global variable between these two functions.
Firstly, it allows the called function to be provided access to different variables at different times. Think how much more laborious it would be to use scanf() if it always saved its results into the same global variables.
Secondly, passing a pointer to another function makes you much more aware of the fact that that function will be able to modify the object. If you use a global variable for the same purpose, it is easy to forget which functions modify the global and which do not.
Thirdly, global variables consume memory for the life of your program. Local variables are released when their containing function ends, and dynamically-allocated data is released when it is freed. So global variables can at times be a considerable waste of memory.
Using pointers leads to the danger of referring to variables that no longer exist, so care has to be taken. But this is most often a problem when there are complicated global or long-lived data structures which in itself is often a design weakness.
Globals just get in the way of good, modular program design and pointers often provide a better way to achieve the same things.
"Pointer" is a variable that tells you how to get to a value: it's the address of the value you care about. You dereference it (with *) to get to the value.
"Global" defines the scope of the variable: anywhere in the program can say the name and get the value.
You can have local pointers, or global non-pointers. The concepts are completely orthogonal.
The term pointer refers to a variable's type; it is a variable used to refer to another. The term global refers to a variables scope - i.e. its visibility from any part of a program. Therefore the question is somewhat nonsensical since they refer to different kinds of variable attribute; a pointer variable may in fact have global scope, and so have both attributes simultaneously.
While a pointer may indeed refer to an object that is not directly in scope (which is what I think you are referring to), it still allows restricted control of scope, because the pointer itself has scope (unless of course it is a global pointer!).
Moreover a global variable always has static storage class. Whereas a pointer may refer to a static, dynamic, or automatic variable, and because it is a variable, the pointer itself may be static, or auto, or in the case of a dynamically allocated array of pointers - dynamic also.
I think perhaps that you are considering only a very specific use of pointers when in fact they have far greater utility and can be used in many ways. For example, you would almost invariably use pointers to implement the links in a linked list data structure; a global variable will not help you do that.
Clifford
Completely different concepts. You can have pointers to both global and local variables. There's nothing associating the two.
Also, from a function, you can certainly return a pointer to a variable scoped within that function. But that's a bad idea since the variable existed on the function's stack and now that's gone.