user7468879
user7468879

Reputation:

What is the use of scanf_s() at the end of my program?

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` ?

Upvotes: 0

Views: 143

Answers (2)

Luke
Luke

Reputation: 1344

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.

Upvotes: 4

John Bollinger
John Bollinger

Reputation: 181064

  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.

Upvotes: 2

Related Questions