I am trying to better understand the behavior of a loop containing some kind of rand () as its final condition. Consider the following example:
for(int i=0; i < rand()%6+10; i++) { do something }
In this case, the cycle will be repeated 10 to 15 times. My question is: will the completion value be evaluated once and then reused for the remaining iterations? or will it be reevaluated with each iteration?
Also, is this considered bad practice?
The condition is evaluated completely before each iteration. (Think about it: how does the compiler know which parts you want to evaluate each time, and which parts you donβt?)
, . , , . , , , .
rand() , i, i . , , , (1) rand() (2) , , . , , .
rand()
i
++ , for:
for
for ( for-init-statement conditionopt ; expressionopt ) statement
:
{ for-init-statement while ( condition) { statement expression ; } }
[: , ; (6.4) , , [...]
, , .
rand() - ... rand() . linux , man 3 rand. , - :
man 3 rand
, .
cppreference std:: rand:
. rand() , ( 1 0 ).rand() , . ++ 11 rand(). ( ++ 11)
. rand() , ( 1 0 ).
rand() , . ++ 11 rand(). ( ++ 11)
, ++ 11, ++ 11, , ?.
rand() , . .
1 int r = rand() % N; [M..N), :1 int r = M + rand() % ( N - M ); , , , . , . , N RAND_MAX. . , . , , , , , , , .
1 int r = rand() % N;
[M..N), :
1 int r = M + rand() % ( N - M );
, , , . , . , N RAND_MAX. . , . , , , , , , , .