152

Here's a question that I don't quite understand:

The command, system("pause"); is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees.

Some people say it is fine to use. Some say it is only to be used when you are locked in your room and no one is watching. Some say that they will personally come to your house and kill you if you use it.

I, myself am a new programmer with no formal programming training. I use it because I was taught to use it. What I don't understand is that if it is not something to be used, then why was I taught to use it? Or, on the flip side, is it really not that bad after all?

What are your thoughts on this subject?

Paul
  • 139,544
  • 27
  • 275
  • 264
Faken
  • 11,352
  • 17
  • 59
  • 74

15 Answers15

97

It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.

Bodging in system("pause") runs the Windows command-line "pause" command and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.

A better idea would be to put a breakpoint at the end and debug it, but that again has problems.

user3840170
  • 26,597
  • 4
  • 30
  • 62
ravuya
  • 8,586
  • 4
  • 30
  • 33
  • 8
    Visual Studio can run the program in two modes: with or without debugging. When run in debugging mode it will stop on first break point. If you don't have one defined it will run the program and close the console. So, if you want the console program to stop, just set a break-point, or, even better, run it without debugging! That will execute the program and stop the console. – Ivan Mesic Jul 17 '13 at 08:02
  • This is not only a feature of Visual Studio - if you run a console program from Windows (i.e. as opposed to loading a command prompt and running it from there), it will also close when it has finished execution. – JBentley Sep 26 '13 at 14:49
  • 3
    **−1** Re “the console window launched from Visual Studio closes when the program has finished execution”, no, only for when the program is run in the debugger. Re “runs the Windows command-line "pause" program”, no there is no such (`pause` is an internal command in `cmd.exe`). The list of better ideas is also severely lacking. – Cheers and hth. - Alf Mar 10 '16 at 08:19
  • I think this answer is the only one that touches on the aspect that this is a workaround. It works around the behaviour of a specific execution environment which closes a terminal window before you can read the program output. What you should do is to fix that environment. If that can't be done, use this workaround, possibly only if `IsDebuggerPresent()` returns true and document this workaround properly ("why is this code here?"). – Ulrich Eckhardt Feb 20 '20 at 16:05
45

It's slow. It's platform dependent. It's insecure.

First: What it does. Calling "system" is literally like typing a command into the windows command prompt. There is a ton of setup and teardown for your application to make such a call - and the overhead is simply ridiculous.

What if a program called "pause" was placed into the user's PATH? Just calling system("pause") only guarantees that a program called "pause" is executed (hope that you don't have your executable named "pause"!)

Simply write your own "Pause()" function that uses _getch. OK, sure, _getch is platform dependent as well (note: it's defined in "conio.h") - but it's much nicer than system() if you are developing on Windows and it has the same effect (though it is your responsibility to provide the text with cout or so).

Basically: why introduce so many potential problems when you can simply add two lines of code and one include and get a much more flexible mechanism?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 66
    For someone complaining about platform dependence, it sure seems strange to suggest `_getch`, _especially_ when standard C++ provides `getchar`. – paxdiablo Oct 19 '12 at 07:14
  • 37
    i feel some irony in calculating overhead for interaction with a human ) – ShPavel Sep 30 '13 at 14:33
  • Perhaps you haven't heard of video games. – orfdorf Dec 30 '14 at 20:33
  • 1
    @Spagpants: Perhaps you don't understand the difference between getting input from a human, and generating images and sounds *at* a human. – yzt Nov 11 '15 at 05:01
  • @yzt Not sure what that's supposed to be in response to. It appears the comment mine was directed at has since been deleted. – orfdorf Nov 11 '15 at 22:19
  • 2
    @Cheersandhth.-Alf - Hm? When I wrote this, 8 years ago, I had just finished debugging an issue that was caused by 'system("pause")' because the executable name of the project was called "pause" and it would go into an infinite loop. My point still stands, I'm not sure why you're saying I was incorrect. –  Jan 13 '18 at 02:27
  • 1
    I literally have no idea what you're on about. Cheers! –  Jan 14 '18 at 19:09
  • 3
    @paxdiablo getchar requires an input and then pressing enter. _getch requires just a keypress no matter what key it is. To emulate _getch on linux you need 5-6 lines of code to change the console mode, and then change it back to default. It's not the same, it does different things. getchar is not a replacement for _getch. – Barnack Oct 30 '19 at 23:58
  • "It's slow." Not compared to the human who will go "Huh press any key? Umm okay..." - locates keyboard - presses Ctrl - nothing happens (dude you can't just press any key!) - scratches head - presses enter. – Lundin Aug 19 '22 at 13:29
32
  • slow: it has to jump through lots of unnecessary Windows code and a separate program for a simple operation
  • not portable: dependent on the pause command
  • not good style: making a system call should only be done when really necessary
  • more typing: system("pause") is longer than getchar()

a simple getchar() should do just fine.

user3840170
  • 26,597
  • 4
  • 30
  • 62
Gavin H
  • 10,274
  • 3
  • 35
  • 42
  • You need to press enter for after pressing some key if you use `getchar()`, its annoying. You can use `#define pause system("pause");` and use it just like you would in CMD script, it's very convenient. – ScienceDiscoverer Jul 24 '22 at 18:30
28

Using system("pause"); is Ungood Practice™ because

  • It's completely unnecessary.
    To keep the program's console window open at the end when you run it from Visual Studio, use Ctrl+F5 to run it without debugging, or else place a breakpoint at the last right brace } of main. So, no problem in Visual Studio. And of course no problem at all when you run it from the command line.

  • It's problematic & annoying
    when you run the program from the command line. For interactive execution you have to press a key at the end to no purpose whatsoever. And for use in automation of some task that pause is very much undesired!

  • It's not portable.
    Unix-land has no standard pause command.

The pause command is an internal cmd.exe command and can't be overridden, as is erroneously claimed in at least one other answer. I.e. it's not a security risk, and the claim that AV programs diagnose it as such is as dubious as the claim of overriding the command (after all, a C++ program invoking system is in position to do itself all that the command interpreter can do, and more). Also, while this way of pausing is extremely inefficient by the usual standards of C++ programming, that doesn't matter at all at the end of a novice's program.

So, the claims in the horde of answers before this are not correct, and the main reason you shouldn't use system("pause") or any other wait command at the end of your main, is the first point above: it's completely unnecessary, it serves absolutely no purpose, it's just very silly.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • 1
    Sometimes an Ungood Practice™ is needed for quick tests.... what we call "quick and dirty" – Michael Haephrati Jan 11 '18 at 19:04
  • Your statement is wrong. It is very useful command that can be used for debugging as a quick break point. – ScienceDiscoverer Jul 24 '22 at 18:27
  • What you do now realise, is that using debugger is also a separate process from your program. It is MUCH more resource hungry than CMD /c pause. So your arguments are NULL. – ScienceDiscoverer Jul 25 '22 at 05:52
  • @MichaelHaephrati It is not "ungood" its totally adequate tool to quickly pause program, if you already `#include `. Why not use the tool? Including windows just for the `pause` is, of cource, not the best idea. – ScienceDiscoverer Jul 25 '22 at 05:53
  • Re @ScienceDiscoverer's three comments: `` is not needed for the `system("pause")` command, and a `system("pause")` command is not needed to keep a console window open. Not sure what the comment about debugger and processes is about; possibly it's a comment here on someone else's answer. – Cheers and hth. - Alf Jul 25 '22 at 19:49
  • Also, Turbo C from 1989 had a similar feature to keep the console window open without getting told to do so (well it had an IDE option to turn this feature on/off iirc). So if your IDE doesn't have this, congrats - you found something even worse than Turbo C for MS DOS from 1989... Now don't go blaming Windows `pause` command for that bad programming IDE. – Lundin Aug 19 '22 at 13:31
22

In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System("PAUSE") because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.

Further explanation in this article.

John T
  • 23,735
  • 11
  • 56
  • 82
16

You can use std::cin.get() from iostream:

#include <iostream> // std::cout, std::cin
using namespace std;

int main() {
   do {
     cout << '\n' << "Press the Enter key to continue.";
   } while (cin.get() != '\n');

   return 0;
}

Besides, system('pause') is slow, and includes a file you probably don't need: stdlib.h. It is platform-dependent, and actually calls up a 'virtual' OS.

Dorian
  • 22,759
  • 8
  • 120
  • 116
Gavriel Feria
  • 415
  • 6
  • 13
11

Because it is not portable.
pause command is a windows / dos only program, so this your code won't run on linux/macOS. Moreover, system is not generally regarded as a very good way to call another program - it is usually better to use CreateProcess or fork or something similar.

Felierix
  • 179
  • 3
  • 12
a_m0d
  • 12,034
  • 15
  • 57
  • 79
3

For me it doesn't make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.

One also doesn't silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.

Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
  • 9
    This is a silly answer. Part of a program "doing its work" is displaying the results of its work to the user. It should therefore not end until the user notifies it that they are finished with it. A program which disappears from the user's screen a nanosecond after it displays its results, is useless. – JBentley Sep 26 '13 at 14:53
  • 1
    @JBentley: I talked about the situation _after_ displaying the results, if any. For displaying results, there exist appropriate patterns, like signals, interrupts, timers, scrollback in your terminal, files. `system("pause")` in itself does not display anything. A command line interface program that is invoked not from the command line and closes too early is invoked wrongly and with the wrong options, and using `system("pause")` to circumvent a wrongly invoked program is really not the right thing to do. – Sebastian Mach Sep 30 '13 at 10:15
  • 1
    I mean, just imagine `cat`, `less`, `vi`, `OpenOffice`, `Mathematica`, `GNU Octave`, what if they'd use `system("pause")`? That would be annoying. – Sebastian Mach Sep 30 '13 at 10:18
  • 2
    Yes, that would be annoying, but now you're specifically talking about the problems of `system("pause")`, whereas your answer talks about "wait before exiting", which is a far more generalised concept. Many of the examples you gave do in fact "wait before exiting", until the user informs the program that they want it to exit. I agree that `system("pause")` is not a good way to achieve that and that there are better solutions, but that isn't what your answer says. – JBentley Sep 30 '13 at 13:28
  • @JBentley: That's right and my fail for being unspecific. I added 'without reason' to my first phrase. – Sebastian Mach Sep 30 '13 at 14:20
  • @JBentley It's not "a silly answer", it is correct. The program's job is _not_ to display the results of its work. Its job is to pass those results to the _standard output_ stream. The technology the user employed to run the program is responsible for displaying those results. The program doing `system("pause")` is the program crossing-over into another land outside of its responsibilities. It's a textbook abstraction leak. – Lightness Races in Orbit Dec 20 '19 at 11:16
  • @LightnessRaceswithMonica My comment was in response to an older version of the answer (since edited in response) and was not about `system("pause")` specifically - see the later comments. – JBentley Dec 20 '19 at 11:36
  • @JBentley There has been only a tiny, editorial change to the answer. Regardless, my comment stands, as addressing the specific claims made in your comment. – Lightness Races in Orbit Dec 20 '19 at 12:05
  • @LightnessRaceswithMonica Then I would respectfully disagree, as applied to the general principle of whether or not programs should display the results of their work and await further input, or simply pass them to the caller and exit. I would agree that that applies in some cases (e.g. the majority of CLI programs). I would disagree in other cases (e.g. a game that is paused and requires you to press a button to resume). The edit may have been tiny but by adding "without reason" it addressed this point. – JBentley Dec 20 '19 at 12:10
  • 1
    @JBentley Oh, absolutely: if a delay/wait/prompt is part of the semantics of the program, `pause` away! – Lightness Races in Orbit Dec 20 '19 at 12:15
3

As listed on the other answers, there are many reasons you can find to avoid this. It all boils down to one reason that makes the rest moot. The System() function is inherently insecure/untrusted, and should not be introduced into a program unless necessary.

For a student assignment, this condition was never met, and for this reason I would fail an assignment without even running the program if a call to this method was present. (This was made clear from the start.)

tshepang
  • 12,111
  • 21
  • 91
  • 136
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
3
system("pause");  

is wrong because it's part of Windows API and so it won't work in other operation systems.

You should try to use just objects from C++ standard library. A better solution will be to write:

cin.get();
return 0;

But it will also cause problems if you have other cins in your code. Because after each cin, you'll tap an Enter or \n which is a white space character. cin ignores this character and leaves it in the buffer zone but cin.get(), gets this remained character. So the control of the program reaches the line return 0 and the console gets closed before letting you see the results.
To solve this, we write the code as follows:

cin.ignore();  
cin.get();  
return 0;
Sepideh Abadpour
  • 2,550
  • 10
  • 52
  • 88
  • 5
    That's slightly misleading. `system()` is standard and not specific to MS Windows. However, the `pause` shell command is a DOS heritage and typically only found there. – Ulrich Eckhardt Feb 20 '20 at 15:33
  • _is wrong because it's part of Windows API and so it won't work in other operation systems._ LOL, so you mean that developing for Windows is wrong? – ScienceDiscoverer Jul 24 '22 at 18:34
  • @ScienceDiscoverer No, I mean that you might want to compile your code to be executable in windows as well as other operating systems (ie. Linux) so you should try to avoid functions that are specific to windows. But if you're sure that you write your code to be executed on just windows then fell free to use `system(pause)` – Sepideh Abadpour Jul 26 '22 at 10:16
1

It doesn't matter.

Adding a system("pause") or getchar() or std::cin.get() or whatever else you like at the end of a console program is there solely for the benefit of the programmer during development. The only purpose of such a line is to ensure that the console won't close before the programmer can view it, when executing the program from inside some IDE that likes to close the console when done executing.

That line will never make it to the production code executable, because why would anyone add "press any key to continue" at the end of a program executed from a console? That's not how sane console program UI works and they never have.

In general, using system() is bad practice but that's another story.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

Here's one reason you shouldn't use it: it's going to piss off most anti-virus programs running on Windows if you're passing the program over to another machine because it's a security threat. Even if your program only consists of a simple cout << "hello world\n"; system("pause"); It's resource heavy and the program gets access to the cmd command, which anti viruses see as a threat.

Andreas DM
  • 10,685
  • 6
  • 35
  • 62
0

the pro's to using system("PAUSE"); while creating the small portions of your program is for debugging it yourself. if you use it to get results of variables before during and after each process you are using to assure that they are working properly.

After testing and moving it into full swing with the rest of the solution you should remove these lines. it is really good when testing an user-defined algorithm and assuring that you are doing things in the proper order for results that you want.

In no means do you want to use this in an application after you have tested it and assured that it is working properly. However it does allow you to keep track of everything that is going on as it happens. Don't use it for End-User apps at all.

  • +1 I use it a lot as a quick breakpoint that works even without IDE. I use `#define pause system("pause");` to get a nice CMD script-like syntax. You can also wrap it around `#define DEBUG` ifdef-else to disable all da pauses in release build. – ScienceDiscoverer Jul 24 '22 at 18:37
0

Next to the arguments provided already (insecurity, slowness, non-portability, ...) there's yet another point missing:

If you are writing production tools of whatever kind then one should keep in mind:

  • Keeping an application window open is not the task of the application! Trying to do so by whatever means (system("pause");, getchar();, getch() or whatever else) is wrong by principle.
  • The application waiting for user input prevents it from being runable in any kind of scripting (bash script, windows batch file, ...), which is a pretty common use case – who should provide the user input there?

These problems would already start if your teacher tried to automise testing your programme with different inputs in his own script (obviously it doesn't...)!

Now if you are just playing around with any kind of testing code that you'll throw away anyway without having been seen by anywhere else (including your teacher) – who should care? Problem then, though, is that you will get used to such practices and will tend to use them even in places where you shouldn't. So best don't get used to right from the start...

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
-3

It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.

Jason A.
  • 71
  • 1
  • 6
  • 8
    *It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often* really doesn't make any sense whatsoever. Noone "invented" this, `pause` was designed for use in DOS batch programs, it was never ever intended to be used in a way like this. Furthermore there were way better alternatives before anyone was ever crazy enough to type the phrase `system("pause");`. – wich Oct 19 '12 at 07:05