When I create a function in C ++ do the variables inside it stay in memory?

2

When I studied pseudocode, I learned that when you call a function and create a variable, it only "exists" when I call that function, for example.

funcao teste():
      x = 10
      retorna x

In case, when I called my test function, it would create the variable x , and after it returned it would erase it.

I am studying C ++ and tried to do this function to generate random numbers.

int gerar_numeros() {
    srand(time(NULL));

    int x = rand() % 100;

    return x;
}

and to assign in the vector this excerpt in the main() function.

for (int c = 0; c <= 10; c++)
    {
        vetor[c] = gerar_numeros();
    }

But the problem is that it only changed the numbers when I ran the script again, eg the first time all the vector values was 5, the second time 10 and so on , then I changed the logic to that one and it worked out.

void gerar_numeros(int vetor[]) {
    srand(time(NULL));

    //int x = 1 + rand() % 100;

    for (int c = 0; c <= 10; c++)
    {
        vetor[c] = rand() % 100;
    }

In the above logic it is as if the variable x was stored in memory, so it always returns the same number.

    
asked by anonymous 12.03.2018 / 00:11

1 answer

6

Variable is a more abstract concept. It is something that helps you understand the memorability of data in your code. What is actually in memory is not the variable. In the code through it you access a memory location where the die is. When you are using the variable it does not exist, just an address.

What you should be talking about is variable scope .

The first missing function creates a memory location that will be accessed by your code with the name of x and there will be a value of 10, then this value is copied to another area because of return and the original value is discarded at the end of the function.

In the second code no variables are needed, just return what you want. But if you're going to call it more than once you can not call srand() on it, this function initializes the random number generator, so every time it's going to the beginning of the list.

One problem has nothing to do with the other. It is not a variable scope problem.

You tried a random solution (did not resist) and got a solution to the problem, but probably not in the most appropriate way.

Since you have already seeded the random seed you can only do this:

int gerar_numeros() { return rand() % 100; }

Note that the numbers are not exactly random, it's called the pseudorandom. It serves a lot, but not for everything. Even C ++ already has a better solution than C, which was used.

    
12.03.2018 / 00:25