简体   繁体   English

具有空主体和条件中的赋值的 while 循环

[英]while-loop with an empty body and an assignment in the condition

I recently encountered the following construct on an abandoned PHP code project:我最近在一个废弃的 PHP 代码项目上遇到了以下构造:


while(($my_var = mt_rand(3, 6))%2 != 0);

(Note the empty body of the loop). (注意循环的空主体)。 This ensures that $my_var is assigned either the number 4 or the number 6.这确保 $my_var 被分配了数字 4 或数字 6。

Is there any (measurable, objective) advantage in using the above construction, over something like使用上述结构是否有任何(可衡量的,客观的)优势,例如

$my_var = mt_rand(2, 3) * 2;

(I am particularly wondering why the author chose to include 3 in the randomization range if the result has to be even anyway.) (我特别想知道如果结果必须是偶数,为什么作者选择将 3 包含在随机化范围内。)

while(($my_var = mt_rand(3, 6))%2;= 0);

This ensures that $my_var is assigned either the number 4 or the number 6.这确保 $my_var 被分配了数字 4 或数字 6。

As @Oli mentioned in comments, this is very convoluted and hard to read.正如@Oli 在评论中提到的那样,这非常令人费解且难以阅读。

And it also has the disadvantage, that you can not really predict how many times it will iterate.它也有一个缺点,就是你无法真正预测它会迭代多少次。

It could (theoretically) “throw the dice” and come up with 5 for the first ten, hundred or thousand iterations... or even never end.它可以(理论上)“掷骰子”并在前十、十或千次迭代中得出 5 个……甚至永远不会结束。 (The implementation of mt_rand is likely good enough for that not to happen, but still.) mt_rand的实现可能已经足够好,不会发生这种情况,但仍然如此。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM