I found out something hilarious problem in C.
Here is my Code
#include <stdio.h>
void method()
{
int indx;
printf("%d\n", indx);
indx ;
}
int main(void)
{
method();
method();
method();
}
This is simple example.
indx variable is not initialized. So, The result of printf in method function would be something strange value.
And indx is local variable. So indx is useless.
But The answer is
0
1
2
It seems like that indx is remain
I can't understand. why?
CodePudding user response:
Local variables are stored on the stack. Because you are doing no other action between each function call, the stack is essentially preserved (unaltered) between calls, and the lack of initialisation means that the value of indx
is whatever happens to be stored in that stack location.
If you made other function calls, the stack might well be overridden, resulting in non-sequential values, and likely not starting from zero.
One reason why the stack might contain zero values at startup can be because, depending on compiler, compiler options and standard library startup, the stack might be deliberately initialised to zero (or just because the region of memory used happens to contain zeros from a previous application etc).
One should never rely on such behaviour, it is specifically undefined behaviour, and thus initialising variables and ensuring you understand variable scope is an important thing to learn in software development.
I think there are plenty of descriptions of how stack is used in software development languages (and variability across hardware architectures and implementations) that you should research that separately.
CodePudding user response:
The local variables are especially stored in the memory area of the corresponding function, hence you can see the increment of the indx value by single value each time the function is called.
But the answer returns the memory values of the stored variable.