Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does while(int) end when int = 0?

I'm trying to find an input in C++ equivalent to Java's in.hasNextInt and I found this.

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  int myint;

  std::cout << "Please enter some integers (enter 0 to end):\n";

  do {
    std::cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";

  return 0;
}

But I don't really get why the input loop would stop when the input is 0. It has the while(myint) loop which also confuses me since myint is an integer and not a boolean. It may work as a boolean when we input something else for myint but I think 0 is still qualified as an integer. Can anyone please explain this to me?

like image 244
Hnim Mahp Avatar asked Dec 08 '22 11:12

Hnim Mahp


2 Answers

The int is converted to a bool implicitly. See here:

The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.

like image 107
Blaze Avatar answered Dec 30 '22 17:12

Blaze


It may work as a boolean when we input something else for myint but I think 0 is still qualified as an integer.

I think this is where your misunderstanding lays. We can't "input something else for myint". It can only ever hold an integer value. If the input stream can't parse an integer, it won't be putting anything into myint, it has nothing to put.

So you can't be checking that myint holds an integer or something else, there is nothing else to hold except integers. As such, the only question is how an integer can be tested for truthiness. As you have been told already, integers are convertible to bools. 0 is false, and anything else is true. That is what the loop condition checks. What it can only ever check at all.

like image 32
StoryTeller - Unslander Monica Avatar answered Dec 30 '22 18:12

StoryTeller - Unslander Monica