0

After the first few months of learning programming at my university I have always been including scanf_s("%d"); at the end of the file or at certain strategic places in my code, in order for the console not to disappear once the program has loaded.

I cannot seem to find a concise answer or an explanation as to:

  1. Why does my console disappear if I do not write scanf_s("%d");
  2. I am using Visual Studio 2015 and have noticed that earlier versions do not require this to be written at the end of the code. Why is this?
  3. Is this considered bad practice` ?
  • `scanf_s("%d");` invokes undefined behaviour. It is clearly wrong and harmful. – too honest for this site Jan 25 '17 at 20:07
  • 1
    1) Because when the end of `main` is reached the program terminates and all its associated resources (including console) are freed. 2) I seriously doubt - unless other (similar) mechanisms that block the program execution are used. 3) One example is any other function that waits for user input (e.g. `getch`). Or to be more generic you can wait until something happens (an event occurs). – CristiFati Jan 25 '17 at 20:08
  • So it `is` considered as bad practice ? Strange that we have been told to do this and to take it as a standard. Any other suggestions as to what I can use? –  Jan 25 '17 at 20:08
  • 1
    @CristiFati: `getch` is not a standard function. Why not use `(void)getchar();`? – too honest for this site Jan 25 '17 at 20:08
  • Here is the solution : http://stackoverflow.com/questions/4118073/how-to-stop-console-from-closing-on-exit – Jean-Baptiste Yunès Jan 25 '17 at 20:11
  • @Ryan: It is not only bad practice, but wrong and illegal code (look up "undefined behaviour"!). Whoever told you should take a C course himself and not teach C to others. Solution: get a better environment, e.g. start your program from a console as stated in the answer below. – too honest for this site Jan 25 '17 at 20:12
  • @Olaf: Indeed, but (on _Win_ only) I prefer `getch` to `getchar` because it returns after any key is pressed (doesn't have to end in _ENTER_). – CristiFati Jan 25 '17 at 20:14
  • 1
    @CristiFati: The correct way is not to have such input at all. For typical console applications which read input from stdin, both are harmful. A better approach is to use a wrapper shell/batch script which manages this problem. (or use an OS which does not defy working with console applications) – too honest for this site Jan 25 '17 at 20:16
  • @Olaf: Again true. But there's a case when the _batch_ /_cmd_ doesn't work (at least not OOTB): when running the code directly from _VStudio_. – CristiFati Jan 25 '17 at 20:20
  • I believe Visual Studio in earlier versions used to have an option in the Debugging settings to prevent the console window from closing when the program exited, but anyway see http://stackoverflow.com/questions/2529617/how-to-stop-c-console-application-from-exiting-immediately – Rob K Jan 25 '17 at 21:11

2 Answers2

4

Windows automatically closes the console programs when they finish execution. scanf_s, as well as scanf, getchar (though be aware there might have been some remaining unprocessed input, often consuming this call) or system("pause") (note - Windows-specific, not recommended) prevent this from happening, forcing the window to stay open expecting input.

Visual Studio might have prevented console from closing in some other way or used some internal console in earlier versions, making this workaround unnecessary. CLion, for example, uses its own console which doesn't suffer from this issue. Also if you launch your program manually from cmd you won't need anything to prevent console from closing - it will just return to the earlier state after your program finished executing.

Luke
  • 1,284
  • 1
  • 12
  • 34
  • You can also add a "busy wait", something like `for(int i = 0; i < BIG_NUMBER; i++);`, that will stall the program until `i` counts up to `BIG_NUMBER`, which can take some time depending how big you make `BIG_NUMBER`. – TezlaCoil Jan 25 '17 at 20:07
  • Can't remember how (long time ago), but I was able to set some parameter in Visual that prevents closing after termination. – Jean-Baptiste Yunès Jan 25 '17 at 20:09
  • 1
    @TezlaCoil That's possible, but apart from being unreliable (you don't know how long it will last, and that time will differ between computers), it will ramp up CPU core usage to 100%. If waiting for a certain period of time is the desired behaviour, there's sleep() function which won't be taxing on the CPU and will last the same time on all machines. – Luke Jan 25 '17 at 20:10
  • We have been told to accept this as a standard. Is it just an easy way of getting around the problem of closing after termination? I am quite sure that previous versions of Visual Studio did not require this. –  Jan 25 '17 at 20:11
  • @Luke, or possibly the compiler will optimize out the busy loop altogether, making it ineffective for delaying program termination. – John Bollinger Jan 25 '17 at 20:13
  • 1
    @TezlaCoil: Never use artificial delays. They will eventually aggrevate the user. – too honest for this site Jan 25 '17 at 20:13
  • @JohnBollinger you're right, I'm actually pretty sure that will happen unless compiling with -O0 (and even then can't guarantee for that) – Luke Jan 25 '17 at 20:14
  • 2
    @Ryan That is a standard workaround for programs which you expect will be launched by the user from a graphical environment (i.e. only in school environments, because CLI user apps are pretty rare these days, and you'd expect from user to launch them from the existing console). It is extremely annoying for someone who is e.g. writing a script calling your program and expecting it to exit cleanly after finishing its job, since this might prevent program halting altogether until something is entered. – Luke Jan 25 '17 at 20:17
  • As for the VS, it's VS-specific behaviour. There might be some kind of flag which will trigger a similar workaround preventing the console to close in the settings, but I haven't tinkered with VS for quite a long time. – Luke Jan 25 '17 at 20:19
  • 1
    @Luke: "CLI user apps are pretty rare these days" - pretty nonsense. Almost every larger server application is console-based. – too honest for this site Jan 25 '17 at 20:19
  • @Olaf I was aiming at regular users with "user apps". I understand there are CLI apps, especially for a headless environment where it's the only way, but in that scenario you really don't want the app to expect input in order to close. – Luke Jan 25 '17 at 20:20
  • Thanks all for your insight and knowledge in this matter. –  Jan 25 '17 at 20:27
2
  1. Why does my console disappear if I do not write scanf_s("%d");

As @Luke already answered, Windows closes the console window when the program running within terminates. The program will not terminate if it is waiting for user input, as scanf_s() and many other I/O functions can make it do.

  1. I am using Visual Studio 2015 and have noticed that earlier versions do not require this to be written at the end of the code. Why is this?

It's news to me that earlier versions of VS behaved differently. This is not a VS-specific behavior, but rather a general Windows behavior. If earlier version behaved differently then that's because those versions of VS made some kind of special provision for running console programs.

  1. Is there any other way of preventing my console from disappearing without the use of scanf_s("%d"); ?

Yes. Open a console window manually and run your program inside, from the command line.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • I have used Visual Studio 2010 last year and I am pretty sure I never had any problems with the console disappearing, and having to use this illegal scanf parameter. It could be that I had a particular setting enabled. –  Jan 25 '17 at 20:13
  • 1
    @Ryan, note that your `scanf()` invokes undefined behavior ("illegal" is meaningless in this context) only because you do not provide an argument corresponding to the field descriptor in the format. It's still *poor practice* to delay termination in this way, but that's a whole other discussion. – John Bollinger Jan 25 '17 at 20:20
  • Thanks for your insight on this matter. Your answer was also very helpful. –  Jan 25 '17 at 20:56