Is it just preference to use an if:break, or while:condition?
Does it matter which you use in some circumstances or is it all just really programmers style? Is there any bad practice in using while (true) and an if condition to break the loop?
I see a lot of python programmers use the the second, while a lot of c++ programmers use the first. Is there a reason for this?
1 2 3 4 5
int y = 0;
while (y != 12){
cout << "while 2:Input 12 to break: " << endl;
cin >> y;
}
1 2 3 4 5 6 7
int x;
while (true){
cout << "while 1: Input 12 to break: " << endl;
cin >> x;
if (x == 12)
break;
}
For this particular case I would use the following loop
1 2 3 4 5 6
int x = 0;
do
{
std::cout << "do-while 3: Input 12 to exit: ";
std::cin >> x;
} while ( x != 12 );
Also take into account that there is a principal difference in your two loops. For the first loop the condition is known before entering the loop. However sometimes the expression in the condition can not be evaluated before entering the loop. In these cases you have to use the while ( true ) loop.
Usually the for loop deals with some sequence where the next element of the secuence is gotten on the base of the previous element. For example
for ( int i = 0; i < 10; i++ ) { /*...*/ }
Here the next value of i is gotten on the base of the previous value of i by incrementing it.
Or another example
for ( Node *p = Head; p; p = p->next ) { /*...*/ }
Again the next pointer to a Node is gotten on the base of the previous pointer.
In the original post the next value used in the condition of the loop have nothing common with the previous value. So I would prefer to use the while loop.