#navi(contents-page-name): No such page: その他

プログラムを終了させる・exit

C言語でプログラムを途中で終了させたい場合は、exit関数を使用します。
以下にサンプルコードと実行例を記します。

c-top.html is not found or not readable.

exit関数の書式

exit関数の書式などは以下の通りです。

exit関数のCサンプルコード

以下にexit関数を使用したCサンプルコードを記します。

exit(0) 正常終了

以下に0(EXIT_SUCCESS)を返却するCサンプルコードを記します。

&ref(): File not found: "exit0.c" at page "その他/Cプログラムを終了・中断させる・exit";(改行コードLF)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("hello\n");

    /* exit 0 */
    exit(EXIT_SUCCESS);

    printf("world!\n");

    return 0;
}

上記のCサンプルコードをコンパイル実行した結果は以下の通りです。

$ gcc exit0.c -o exit0
$ ./exit0 
hello
$ echo $?
0

exit(1) 異常終了

以下に1(EXIT_FAILURE)を返却するCサンプルコードを記します。

&ref(): File not found: "exit1.c" at page "その他/Cプログラムを終了・中断させる・exit";(改行コードLF)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("hello\n");

    /* exit 1 */
    exit(EXIT_FAILURE);

    printf("world!\n");

    return 0;
}

上記のCサンプルコードをコンパイル実行した結果は以下の通りです。

$ gcc exit1.c -o exit1
$ ./exit1 
hello
$ echo $?
1

exit(任意の値)

以下に任意の値である123を返却するCサンプルコードを記します。

&ref(): File not found: "exit123.c" at page "その他/Cプログラムを終了・中断させる・exit";(改行コードLF)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("hello\n");

    /* exit 123 */
    exit(123);

    printf("world!\n");

    return 0;
}

上記のCサンプルコードをコンパイル実行した結果は以下の通りです。

$ gcc exit123.c -o exit123
$ ./exit123
hello
$ echo $?
123

以上、exit関数のCサンプルコードと実行結果でした。

c-btm.html is not found or not readable.

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS