2
What is the difference between infinite loops for(;;)
and while(true)
?
Is there any advantage or disadvantage of using one or the other?
For example, in a simple terminal input validation code, to validate numbers int between 0 and 100:
#include <iostream>
using namespace std;
int main(void)
{
int valor;
//For
for (;;)
{
cout << "Insira o valor: " << endl; cin >> valor;
if (valor > 0 && valor <= 100)
{
break;
}
else
{
cout << "Por favor, insira um valor valido: " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
//While
while (true)
{
cout << "Insira o valor: " << endl; cin >> valor;
if (valor > 0 && valor <= 100)
{
break;
}
else
{
cout << "Por favor, insira um valor valido: " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
return 0;
}
Related: Is there any difference between an infinite loop with for and while? | Difference between while and for | How the for works(;;)?
– Woss
I find more duplicate of this answer: Is there any difference between an infinite loop with for and while?. Than the one marked as a duplicate of common for and while... I hadn’t found the other answer as I used the wrong Keywords.
– danieltakeshi