Reset variable

Asked

Viewed 120 times

3

Is there any way to reset the variable without assigning all values again? ex:

int number = 5 + rand() % 5 + 1;
cout << number << endl;
cout << number << endl;

If the randomization is equal to 3, in the two Couts they would return 8. I would like something like: redefine(number);

Thus remaining:

int number = 5 + rand() % 5 + 1;
cout << number << endl;
redefine(number);
cout << number << endl;

So it would return 8 and another numbero. ps: Without having to write all the variable definition again.

  • I don’t know if I understand what you want. You want the expression that was assigned to number run again? Have you seen this in any other language?

2 answers

4


If I understand what you want, exactly this way is not possible and I do not know a way to do it in any language.

It is possible to do something different that produces the desired result using a function.

int gerador() {
    return 5 + rand() % 5 + 1;
}

int main() {
    int number = gerador();
    cout << number << endl;
    number = gerador();
    cout << number << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

There is a more simplified syntax called lambda in C++11 but it does not exist exactly for this type of use. It would be something like this:

int main() {
    auto gerador = []() { return 5 + rand() % 5 + 1; };
    int number = gerador();
    cout << number << endl;
    number = gerador();
    cout << number << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I don’t know if you noticed, since you didn’t start the random generation with some number caught in the case, it always generates the same sequence of numbers in each run since this generation is pseudo-random. To boot is common to do srand(time(0));

  • I wanted to know if there was any way. I got it. As for srand, I’m aware. Thank you.

1

Variables serve to keep information. Maybe what you need is a function?

int get_number() {
    return 5 + rand() % 5 + 1;
}

int main() {
    cout << get_number() << endl;
    cout << get_number() << endl;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.