Originally Posted by
Enoz28
Hello,
I'm trying to return a value in a function, but the value return by the function is exceedingly high and random. Is there a way to zero out the function variable so that when the function is called it starts at zero.
It sounds like you're doing this:
Code:
#include <stdio.h>
int foo( void )
{
int x;
return x;
}
int main( void )
{
printf("%d\n", foo( ) );
return 0;
}
Since x is not initialized, it will store some arbitrary value, and as such, will give you the results you've described. There are a few ways to fix this:
1) Make the variable static:
Code:
int foo( void )
{
static int x;
return x;
}
Static variables are automaticly initialized to zero.
2) Initialize the variable yourself.
Code:
int foo( void )
{
int x = 0
return x;
}
Since you're initializing it manually, and since this function does nothing more, it will simply return what you initialize it to.
3) Make your function meaningful, so it actually does something with the variable, rather than just return some otherwise meaningless value. Personally, I'd go this route.
Code:
int foo( void )
{
int x;
/* actually use x here and do something with it */
return x;
}
That being said, the #2 option is also highly suggested. You should always initialize your variables to something before using them. Always. Thus, the final version would be something akin to this:
Code:
int foo( void )
{
int x = 0;
/* actually use x here and do something with it */
return x;
}
Now then, you could have used static also, however, this assumes you really want the full benifit of using the static keyword, and aren't just only using it for the lazy-man's initialization. (Since it has more than that effect.)
Quzah.