Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'.
In all the examples i've attempted so far I've had to use getch() to hold open the command prompt, and sometimes remove the return 0 statement from the end of the main method.
Is this a vagary of windows 7 and will it cause problems further down the line? It's no problem doing this at the moment but since this is not included in the book I was wondering if it might be something I've set up wrong.
Many Thanks :)
Use _getch() in place of getch()
When a program ends, any resources created by that program including the terminal window will be released. By using getch you prevent the program from ending. This is normal behavior and should continue to work that way until Windows is a distant memory.
If you start the program from within an already existing command window, the window will not close because it wasn't created by the program.
getch()
is not operating system specific, but it is not directly portable. The preferred method for doing this inC++
is to usestd::cin.get();
.The
main
function canreturn 0
implicitly (you don't need to actually have that code, see below).See this question for more details about the implicit
return 0
frommain
.First,
getch()
isn't a standard C or C++ function. Even under Windows, I think its use is deprecated; its semantics go back to CP/M and early MS-DOS.Secondly, it really isn't necessary, at least not for console apps (and I don't think it's available for non-console apps). If you're running the program from a console window, the window stays open. And if you're running it from Visual Studios, it's trivial to set a breakpoint on the return statement, which blocks the program, and keeps the window open (although there's really no reason for the IDE to close it just because your program has terminated).