I was wondering on if it was possible to reset all values in a program so that when i call main() to restart my program all the ints and arrays are back to their default values.
Thanks everybody!
P.S. I declared all my values above my main().
No, you have to do it manually since you are using global variables.
Related
noob here
I've been doing a lot of research into how to initialize variables in C. I've concluded that it is good practice to always initialize variables. However, I haven't found a definitive answer as to how to initialize variables. For example, how do you initialize a char and a string? Sure you could initialize them however you want, but what is a good zero/blank value to use?
int a = 0;
char b = ?;
char c[] = ???;
Also, what about if you declare and define a variable in a basic program and then use scanf() to get the value from the user? Should you still initialize the variable before you use scanf()?
Thank you in advance.
Initializing variables with zero/dummy/blank values is a bad practice that should be avoided. Not only it makes no sense, it can prevent modern compiler run-time code sanitization tools from detecting read access to variables that have not been assigned proper values.
In modern C you can declare variables anywhere in the executable code. The greatest benefit of this feature is that almost always you can initialize such variables with meaningful values, instead of just zero/dummy/blank values. Take advantage of this. Strive to declare your variables locally, where you are ready to immediately initialize them with meaningful values.
In those rare cases when you have no meaningful value to initialize your variable with, it might be a better idea to leave it uninitialized, instead of initializing it with zero. There are exceptions from this guideline, but they are rare.
Generally speaking, if a variable is going to unconditionally have a value assigned to it at some point after it is declared but before it is read, you don't need to initialize it. You example of the address of a variable being passed to scanf () is a good example of a variable that doesn't need to be initialized.
If a variable needs to have some kind of default value, that's when you need to initialize it. If you find that a variable is read before it is written to, that's a good sign that it needs to be initialized.
I'm currently working on a program which picks up input(via main) and draws different fractals depending on the input.
I'm saving the parsed and converted(to a number)user input, in a structure:
typedef struct
{
unsigned int xcord,ycord;
}point_t;
typedef struct
{
int fractalType;
double lstart,lend,lconstant;
double leftangle,rightangle;
point_t drawStart;
}input_data_t;
The problem I'm having is that certain fractals don't use all the variables contained in the structure, and if a certain fractal is called with a variables it doesn't use I must show an error.
Anyways now on to the problem, I know that variables when DECLARED "pick up " garbage from what was before hand in the assigned memory position. Is there any way to know if a variable has been initialized during run time, as to insure after parsing that no unnecessary variable has been used? (If so I need a cross platform solution)
No, there is no way to find this out directly. Reading from an uninitialized variable invokes undefined behavior and there is no way to recover from that. However, you have a few options to prevent this from happening.
If your variables have meaningful default values, just initialize them to those defaults before doing anything else with them. You still won't be able to tell the difference between a variable that was defaulted and one that just happens to have the same value but if your logic works without that knowledge, then this is perfectly fine. (For example, if you were to plot a sine function f(x) = a + b sin(c x + d), it would be natural to default a and d to 0 and b and c to 1.)
If your parameters don't span the entire value range of the data type, you could initialize them to some sentinel value and check for that before using them. For example, you could use NAN for floating-point values or −1 for quantities of any type that cannot be negative. Many people dislike this solution because it is all too easy to forget checking the value and using the sentinel as if it were a proper value, thus computing garbage. I believe that there is a time and place for every technique but this one is probably indeed overused.
If everything else fails, you can add a flag per variable that indicates whether it has a value. To make this usable, I recommend you create a data type with a reasonable name such as this one.
struct optional_float
{
bool initialized; // always safe to read, set appropriately
float value; // only safe to read if initialized == true
};
In C++, you can do much better by using the new std::experimental::optional<T>. But I realize that the C++ tag was removed from your question.
Finally, be sure to run your code through a debugger such as Valgrind or use a sanitizer to detect accidental reads from uninitialized variables.
I don't think there is method to check a variable wether initialiez or not .
As default variable in c has a random value or 0 before you initialize it.
If you want to know wether a variable is initialzed ,you can make a legal value scope of this variable. Before you use it ,you can check wether the value is inside the scope.
The best method in c to safty using variables is checking it by yourself if you are to use it.
why not just initialize that struct with some invalid value, then the problem become whether the value is invalid.
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.
I was hoping to get help with the below question.
In VBA programming there is a syntax which can be used to assign the value vbNullstring to a variable before you assign any data to it, this way you ensure a fresh start to your variable and the data saved onto it.
How do you do the above in C language? I'm currently running a step-by-step debug of my code and I've added a few 'watch' processes to my key variables so that I can keep track of what my code is assigning it. Here's my confusion and hence the above question...my program has not even begun to assign any data to my variables and yet on my 'watch' tab i see that these variables are carrying different values already like 19924000669 for int variables and "(\0\002\0\0\0Ay..." for char variables. How do I get rid of these initial values and show an empty initial value for all my variables before the code assigns any data to it?
Thanks,
J
There are no "initial" values in C. Or rather, there are no meaningful values - C doesn't require that the compiler initialize variables to any value (some compilers do, so it depends on the compiler - read your compiler manual).
What you're seeing is "noise". When you turn on your computer, the value of data in your RAM is random. Set by various physical processes from thermal noise to cosmic background radiation. Also, when you're running a program in an OS, when you free some memory back to the OS or when your program quits the OS generally doesn't reformat that memory to any value. So you may also be seeing data that's there from previous running programs.
The traditional solution in C is to initialize the variable with the value zero (0) or if it's a pointer, NULL.
If you need to know if something is actually data or uninitialized then use a struct with a member (something called defined?) that keeps track of the initialized state and set that to 0 or 1. That's what VB (or Javascript or Perl etc.) is doing behind the scenes anyway.
C doesn't have the "feature" of undefined values because C deals directly with hardware. And bits are either on or off - digital electronics doesn't really like any other values - so variables muse be either 0 or not 0.
When you declare a variable you can specify an initial value, e.g.
int intvar = 0;
char str[10] = "";
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)