0

I have a Question About While Loop.

int space = 4;
while(space){
    cout<< "*";
    space --;
}

This While Loop will run 4 times and stop when value reaches to Zero 0, So my Question is we do not specify any condition like while(space > 0){...} then why it Stop.

Or this Zero 0 consider as False , and first our while loop is true and when Reaches to 0 it becomes False and Stop.

Please Tell me , i am little confused about it.

  • @GoswinvonBrederlow make that an answer. – lorro Jul 01 '22 at 19:56
  • Take a look at [implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion) or this Q&A: https://stackoverflow.com/questions/31551888/casting-int-to-bool-in-c-c . – Bob__ Jul 01 '22 at 20:03

2 Answers2

2

int gets converted to bool in a boolean context using space != 0.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
1

The while loop takes a condition which is a bool. In this case, you've passed in an int instead, which will get implicitly converted to bool. That bool will be false if the int is 0, and will be true for any other value.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
thedemons
  • 1,139
  • 2
  • 9
  • 25