You are here:

C/C programming

Advertisement


Question
how do i declare an ESC button, so that when user presses it the program terminates?

Answer
Hi, Tumelo.

The simplest way to do this is to use the exit function.  The format of the exit function is:

   void exit(int exitCode)

The parameter is the exit code, or the return value given by the application.  Generally, 0 is used to indicate a successful execution and some other value is considered an error.  This is mere convention, and is not a strict guideline.  You can use whatever you like for that parameter.

The exit function immediately ceases execution of the program and returns the value passed in as the exit code.  So, if you have some fatal error or some other immediate exit condition, this is a good function to use to close the program without further execution.

In your case, you say you want an ESC button.  I don't know if you mean a graphical button or if this is a simple console application and you just need to capture the input of some button and use it to close the program.  In either case, whatever method of receiving the escape request, just call the exit function from within the handling code.  For example:

   void escapePressed()
   {
       printf("ESC pressed, halting execution.\n");
       exit(0);
   }

I hope that answers your question.  If you have any further questions, please, do not hesitate to ask.  I am here to help. :)

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2012 About.com, a part of The New York Times Company. All rights reserved.