if varianbles are declared within a function, do they die when the function finish?
if varianbles are declared within a function, do they die when the function finish?
If you allocate memory for them with new, then the memory is still valid after the function ends and doesn't die until you delete it.
The memory space will still be avialable until you delete it, however any local pointers you have in the function will be destroyed when the function ends, so unless you are saving the pointer somehow (return value or static) then that memory space is effectivaly lost.
ok, i see how it works. i was just working with random numbers and i came up with another question. lkook at my code:
i have a function thats supposed to generate random numbers and reutnr them, but everytime i run the program, i get the same result. why isn't this random?Code:#include <iostream> #include <conio.h> using namespace std; int generate_numbers(int low, int high) { time_t seconds; time (&seconds); return (rand() % (high - low + 1) + low); } int main() { int number[10]; int i; for (i = 0; i < 10; i++) number[i] = generate_numbers(1, 100); for (i = 0; i < 10; i++) cout << number[i] << endl; getch(); return 0; }
I have run experiments on an xp machine.
I ran a program with initialization and declaration of a variable inside a function.
Local scope without being declared as static.
I monitored the memory usage per the system log.
The memory was still being used by the system after the exit of the function.
It didn't release the memory back to the system resource pool until after the program itself was dead. I think the adress that keeps track of the memory is dead after the function ends, but the memory itself is still concidered active in the program until the program itself dies. This could all be system dependent though. Windows does some weird things sometimes.
"Hence to fight and conquer in all your battles is not supreme excellence;
supreme excellence consists in breaking the enemy's resistance without fighting."
Art of War Sun Tzu
Ok are you getting different numbers for each call?
The reason you would get the same set of numbers each time you run the program is because you aren't initalizing the random number generator.
Search the board and you'll find about a million posts about it.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]