c++ - FOR loop without condition value "for (int i = 1; ; i++)" doesn't work properly -


i found post loop used without condition value. here loop:

for (initialization; condition; afterthought)  {     // code for-loop's body goes here. } 

it's not safe skip condition value, if use if/else statement can done. please take on loop: for (int = 1; ; i++) , implementation inside. reason, don't proper logic if/else statement.

#include <iostream> using namespace std;  int main() {      int boxes;     int boxes_for_sale;      cout << "enter quantity of boxes in warehouse: > " << flush;     cin >> boxes;     cout << "enter quantity of boxes sale: > " << flush;     cin >> boxes_for_sale;      (int = 1;; i++) {          if (boxes < boxes_for_sale) {             cout << "there not enough boxes in warehouse!" << endl;             cout << "enter quantity of boxes sale: > " << flush;             cin >> boxes_for_sale;         }         else             boxes -= boxes_for_sale;             cout << "car n:" << << " full\n" << "you have " << boxes << "boxes sale" << endl;          if (boxes == 0)             cout << "sold out!" << endl;             break;      }     return 0; } 

since did not specify desired behaviour of program, state happening in code right now.

important snippets of code may doing unexpected:

 (int = 1;; i++)  

this legal, notice there no termination condition specified. run infinite loop unless break out of it.

else     boxes -= boxes_for_sale;     cout << "car n:" << << " full\n" <<     "you have " << boxes << "boxes sale" << endl; 

i can guess based on indentation want both lines execute when if statement preceding else false, not happening.

since have not specified else block curly braces, first statement after else execute when need to. cout always execute.

you have same issue with:

if (boxes == 0)         cout << "sold out!" << endl; //will output if boxes==0         break; //will break out of loop in case 

Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -