3
#include <iostream>
#include <string>

int main()
{
  std::string name;
  std::cout << "What is your name? ";
  getline (std::cin, name);
  std::cout << "Hello, " << name << "!\n";
  while (true);
  std::cout<<"over";
}

Program outputs “What is your name” and I input my name, say “Dom”, but the program then waits there. Why doesn’t it show “Hello Dom!” before it gets stuck at the while loop?

  • I'm sorry but the behavior of your program is undefined! Anything is allowed to happen. See the "Progress guarantee" heading here: https://en.cppreference.com/w/cpp/language/memory_model – alter_igel Jul 30 '19 at 21:09
  • I dont agree with the dupe, because [infinite loops without side effects](https://en.cppreference.com/w/cpp/language/ub) are ub – 463035818_is_not_an_ai Jul 30 '19 at 21:10
  • @formerlyknownas_463035818 Good news is you can unilaterally re-close the post as a duplicate and edit the dupe list. – NathanOliver Jul 30 '19 at 21:13
  • Did you press enter / did you input a newline after you inputted "Dom"? – KamilCuk Jul 30 '19 at 21:13
  • @NathanOliver yeah I know, was looking for the old dupe .. and found it – 463035818_is_not_an_ai Jul 30 '19 at 21:13
  • 2
    The reason the code never shows "Hello, Dom!" is because std::cout happens not to flush itself before the while loop executes; not because the while(true) loop invokes UB. The while(true) loop *is* UB, but in this case the compiler acts sensibly and simply never exits it – Alecto Irene Perez Jul 30 '19 at 22:15

0 Answers0