Why does entering '0' terminate do-while loop here?

  • Thread starter Thread starter deltapapazulu
  • Start date Start date
  • Tags Tags
    Loop
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
deltapapazulu
Messages
84
Reaction score
13
I am relatively new to programming and C++ and for the life of me I can't figure out why entering a '0' as input in the do-while loop here terminates the loop.
Code:
// vector::push_back
#include <iostream>
#include <vector>

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

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

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

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

  return 0;
}
 
Physics news on Phys.org
Zero means false in C++ a holdover from C programming.

https://www.le.ac.uk/users/rjm1/cotter/page_37.htm

http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=bool
 
  • Like
Likes   Reactions: Asymptotic
What's happening is that your int is being implicitly cast to a boolean. This is explicitly what you are doing.
C:
do {
   std::cin >> myint;
   myvector.push_back (myint);
  } while (static_cast<bool>(myint));
If you use the -Wall compiler option, you should get a warning about the implicit cast.
This also works for things other than ints. It's very common to check for pointers this way.
C:
FILE * fp = fopen("/tmp/file", "wb");
if (fp){
   //write to file because it's open
} else {
   std::cerr << "Was not able to open file" << std::endl;
}
fclose(fp);