Reset variable

2

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

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

If the randomization is equal to 3, in both cout's would return 8. Would you like something like: redefine (number);

Looking like this:

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

So I would return 8 and another number. ps: Without having to write the whole definition of the variable again.

    
asked by anonymous 21.12.2014 / 04:41

2 answers

3

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

You can 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;
}

See running on ideone .

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

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

See running on ideone .

I do not know if you noticed, since you did not initialize the generation of random numbers with a number taken to the case, it always generates the same sequence of numbers in each execution since this generation is pseudorandom. To initialize it is common to do srand(time(0));

    
21.12.2014 / 05:15
1

Variables serve for save 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;
}
    
21.12.2014 / 05:14