Could you tell me the mean of this code?
while(1)
{ // do something
thanks!
Its a way of starting an infinite loop which will be stopped using some means other than the condition inside the brackets next to while.
eg,
void somefunc()
{
std::string str;
while(true)
{
std::getline(cin, str);
if( str == "quit" )
return;
else
std::cout << "You Typed: " << str << std::endl;
}
}
IMHO, this kind of idiom is seldom useful - unless you have some compelling reason to do otherwise, you should put an exit condition in the while brackets
Personally, I sometimes use while(1) or similar for things like menus, where choosing a menu option would cause the program to do something and then return to the menu. Then, if you want to exit the program, just return 0 to end the program:
int main()
{
int bob;
while(1)
{
cout << "Enter a number to display, or -1 to exit: ";
cin >> bob;
if(bob == -1) { return 0; }
cout << bob << endl;
}
}
However, some form of exit condition works better, like this:
int main()
{
int bob;
char exit = false;
while(!exit)
{
cout << "Enter a number to display, or -1 to exit: ";
if(bob == -1) { exit = true; }
else { cout << bob << endl; }
}
}
Of course, your program would probably be a little more complicated.
Edit: Ha, totally didn't see that it had already been answered. My bad!
Personally, I sometimes use while(1) or similar for things like menus, where choosing a menu option would cause the program to do something and then return to the menu. Then, if you want to exit the program, just return 0 to end the program:
int main() { int bob; while(1) { cout << "Enter a number to display, or -1 to exit: "; cin >> bob; if(bob == -1) { return 0; } cout << bob << endl; } }
This is generally not recommended, although it does work. The reason is you are burying the exit from the function/program in the middle of your code. This could be a maintenance nightmare for the team that inherits your program (or for you in 2 months :icon_wink:) It would be best to break out of the loop and return at the bottom of the function.
thank you for your helps :)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.