logo

Функція exit() у C

The функція exit(). використовується для негайного завершення виклику процесу або функції в програмі. Це означає, що будь-який відкритий файл або функція, що належить процесу, закривається негайно, коли в програмі виконується функція exit(). Функція exit() є стандартною бібліотечною функцією C, яка визначена в stdlib.h файл заголовка. Отже, ми можемо сказати, що це функція, яка примусово завершує поточну програму та передає керування операційній системі для виходу з програми. Функція exit(0) визначає завершення програми без повідомлення про помилку, а потім функція exit(1) визначає, що програма примусово завершує процес виконання.

Функція exit() у C

Важливі моменти функції exit().

Нижче наведено основні моменти функції виходу в програмуванні на C:

  1. Під час використання функції exit () ми повинні включити файл заголовка stdlib.h.
  2. Він використовується для припинення нормального виконання програми під час виявлення функції exit ().
  3. Функція exit () викликає зареєстровану функцію atexit () у порядку, зворотному їх реєстрації.
  4. Ми можемо використовувати функцію exit(), щоб скинути або очистити всі дані відкритого потоку, такі як читання або запис із незаписаними буферизованими даними.
  5. Він закрив усі відкриті файли, пов’язані з батьківською або іншою функцією чи файлом, і може видалити всі файли, створені функцією tmpfile.
  6. Поведінка програми не визначена, якщо користувач викликає функцію виходу більше ніж один раз або викликає функцію виходу та функції quick_exit.
  7. Функція виходу поділяється на дві частини: вихід (0) і вихід (1).

Синтаксис функції exit().

 void exit ( int status); 

The вихід() функція не має типу повернення.

js onload

int статус: Він представляє значення статусу функції виходу, що повертається до батьківського процесу.

Приклад 1: програма для використання функції exit() у циклі for

Давайте створимо програму для демонстрації функції виходу (0) для нормального завершення процесу на мові програмування C.

скільки нулів в 1 мільярді
 #include #include int main () { // declaration of the variables int i, num; printf ( &apos; Enter the last number: &apos;); scanf ( &apos; %d&apos;, &amp;num); for ( i = 1; i<num; 0 6 i++) { use if statement to check the condition ( i="=" ) * exit () with passing argument show termination of program without any error message. exit(0); else printf (' 
 number is %d', i); } return 0; < pre> <p> <strong>Output</strong> </p> <pre> Enter the last number: 10 Number is 1 Number is 2 Number is 3 Number is 4 Number is 5 </pre> <h3>There are two types of exit status in C</h3> <p>Following are the types of the exit function in the C programming language, as follows:</p> <ol class="points"> <li>EXIT_ SUCCESS</li> <li>EXIT_FAILURE</li> </ol> <p> <strong>EXIT_SUCCESS</strong> : The EXIT_ SUCCESS is the exit() function type, which is represented by the exit(0) statement. Where the &apos;0&apos; represents the successful termination of the program without any error, or programming failure occurs during the program&apos;s execution.</p> <p> <strong>Syntax of the EXIT SUCCESS</strong> </p> <pre> exit (EXIT_SUCCESS); </pre> <p> <strong>Example 1: Program to demonstrate the usage of the EXIT_SUCCESS or exit(0) function</strong> </p> <p>Let&apos;s create a simple program to demonstrate the working of the exit(0) function in C programming.</p> <pre> #include #include int main () { printf ( &apos; Start the execution of the program. 
&apos;); printf (&apos; Exit from the program. 
 &apos;); // use exit (0) function to successfully execute the program exit (0); printf ( &apos;Terminate the execution of the program.
 &apos;); return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Start the execution of the program. Exit from the program. </pre> <p> <strong>Example 2: Program to use the EXIT_SUCCESS macro in the exit() function</strong> </p> <p>Let&apos;s create a C program to validate the whether the character is presents or not.</p> <pre> #include #include int main () { // declaration of the character type variable char ch; printf(&apos; Enter the character: &apos;); scanf (&apos; %c&apos;, &amp;ch); // use if statement to check the condition if ( ch == &apos;Y&apos;) { printf(&apos; Great, you did it. &apos;); exit(EXIT_SUCCESS); // use exit() function to terminate the execution of a program } else { printf (&apos; You entered wrong character!! &apos;); } return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Enter the character: Y Great, you did it. </pre> <p> <strong>EXIT_FAILURE</strong> : The EXIT_FAILURE is the macro of the exit() function to abnormally execute and terminate the program. The EXIT_FAILURE is also represented as the exit(1) function. Whether the &apos;1&apos; represents the abnormally terminates the program and transfer the control to the operating system.</p> <p> <strong>Syntax of the EXIT_FAILURE</strong> </p> <pre> exit (EXIT_FAILURE); </pre> <p> <strong>Example 1: Let&apos;s create a program to use the EXIT_FAILURE or exit(1) function</strong> </p> <pre> #include #include int main () { int num1, num2; printf (&apos; Enter the num1: &apos;); scanf (&apos;%d&apos;, &amp;num1); printf (&apos; 
 Enter the num2: &apos;); scanf (&apos;%d&apos;, &amp;num2); if (num2 == 0) { printf (&apos; 
 Dividend cannot be zero. &apos;); // use EXIT_FAILURE exit(1); } float num3 = (float)num1 / (float)num2; printf (&apos; %d / %d : %f&apos;, num1, num2, num3); // use the EXIT_SUCCESS exit(0); } </pre> <p> <strong>Output</strong> </p> <pre> Enter the num1: 20 Enter the num2: 6 20 / 6 : 3.333333 2nd Run Enter the num1: 20 Enter the num2: 6 Dividend cannot be zero </pre> <p> <strong>Example 2: Let&apos;s create another program to use the EXIT_FAILURE to terminate the C program.</strong> </p> <pre> #include #include int main () { // declare the data type of a file FILE *fptr = fopen ( &apos;javatpoint.txt&apos;, &apos;r&apos; ); // use if statement to check whether the fptr is null or not. if ( fptr == NULL) { fprintf ( stderr, &apos;Unable to open the defined file 
&apos; ); exit ( EXIT_FAILURE); // use exit function to check termination } // use fclose function to close the file pointer fclose (fptr); printf ( &apos; Normal termination of the program. &apos;); return 0; } </pre> <p> <strong>Output</strong> </p> <pre> Unable to open the defined file. </pre> <hr></num;>

У C існує два типи статусу виходу

Нижче наведено типи функції виходу в мові програмування C:

  1. ВИХІД_ УСПІХ
  2. EXIT_FAILURE

EXIT_SUCCESS : EXIT_SUCCESS — це тип функції exit(), який представлений інструкцією exit(0). Де «0» означає успішне завершення програми без будь-яких помилок, або помилка програмування сталася під час виконання програми.

Синтаксис EXIT SUCCESS

 exit (EXIT_SUCCESS); 

Приклад 1: програма для демонстрації використання функції EXIT_SUCCESS або exit(0).

Давайте створимо просту програму, щоб продемонструвати роботу функції exit(0) у програмуванні на C.

 #include #include int main () { printf ( &apos; Start the execution of the program. 
&apos;); printf (&apos; Exit from the program. 
 &apos;); // use exit (0) function to successfully execute the program exit (0); printf ( &apos;Terminate the execution of the program.
 &apos;); return 0; } 

Вихід

 Start the execution of the program. Exit from the program. 

Приклад 2: Програма для використання макросу EXIT_SUCCESS у функції exit().

висота зсуву

Давайте створимо програму на C, щоб перевірити, присутній символ чи ні.

 #include #include int main () { // declaration of the character type variable char ch; printf(&apos; Enter the character: &apos;); scanf (&apos; %c&apos;, &amp;ch); // use if statement to check the condition if ( ch == &apos;Y&apos;) { printf(&apos; Great, you did it. &apos;); exit(EXIT_SUCCESS); // use exit() function to terminate the execution of a program } else { printf (&apos; You entered wrong character!! &apos;); } return 0; } 

Вихід

 Enter the character: Y Great, you did it. 

EXIT_FAILURE : EXIT_FAILURE — це макрос функції exit() для ненормального виконання та завершення програми. EXIT_FAILURE також представлено як функція exit(1). Якщо «1» означає аномальне завершення програми та передачу керування операційній системі.

Синтаксис EXIT_FAILURE

інакше java
 exit (EXIT_FAILURE); 

Приклад 1. Давайте створимо програму для використання функції EXIT_FAILURE або exit(1).

 #include #include int main () { int num1, num2; printf (&apos; Enter the num1: &apos;); scanf (&apos;%d&apos;, &amp;num1); printf (&apos; 
 Enter the num2: &apos;); scanf (&apos;%d&apos;, &amp;num2); if (num2 == 0) { printf (&apos; 
 Dividend cannot be zero. &apos;); // use EXIT_FAILURE exit(1); } float num3 = (float)num1 / (float)num2; printf (&apos; %d / %d : %f&apos;, num1, num2, num3); // use the EXIT_SUCCESS exit(0); } 

Вихід

 Enter the num1: 20 Enter the num2: 6 20 / 6 : 3.333333 2nd Run Enter the num1: 20 Enter the num2: 6 Dividend cannot be zero 

Приклад 2: Давайте створимо іншу програму, яка використовуватиме EXIT_FAILURE для завершення програми C.

 #include #include int main () { // declare the data type of a file FILE *fptr = fopen ( &apos;javatpoint.txt&apos;, &apos;r&apos; ); // use if statement to check whether the fptr is null or not. if ( fptr == NULL) { fprintf ( stderr, &apos;Unable to open the defined file 
&apos; ); exit ( EXIT_FAILURE); // use exit function to check termination } // use fclose function to close the file pointer fclose (fptr); printf ( &apos; Normal termination of the program. &apos;); return 0; } 

Вихід

 Unable to open the defined file.