【C言語サンプル】
今時の Hello world!
(C89/90を捨てC99へ移行)

c99仕様のC言語では
main 末尾の return 0 は書かなくてもOK!

#include <stdio.h>
int main(void)
{
    printf("Hello, World!\n");
}

C89仕様のC言語:30年以上前の古い仕様

gcc hello.c -Wall -std=c89 でコンパイルすると
gccにmain のreturnが無いと怒られる。

C99仕様のC言語:20年以上の実績

gcc hello.c -Wall -std=c99でコンパイルすると
gccに怒られない。


プログラム品質を重視するならば

早く時代遅れのC89を捨て、
C99へ移行し新機能の恩恵を享受しましょう。


ハローワールドでよく出る警告の修正方法

main()
{
    printf("Hello world\n");
}

K&Rという古い仕様で記述しているので最近のコンパイラでは警告がたくさん出ます。


/*warning: return type defaults to ‘int’ [-Wreturn-type] を消す*/
 int main(void) 
{
    printf("Hello world\n");
}

関数main(void) の前に int 型を明示するとwarning: return type defaults to ‘int’ [-Wreturn-type] が消えます。


/*warning: implicit declaration of function ‘printf’ を消す*/
#include    <stdio.h>
int main(void)
{
    printf("Hello world\n");
}

printf()関数のプロトタイプ宣言が記述された<stdio.h> を include すると warning: implicit declaration of function ‘printf’ が消えます。


/* warning: control reaches end of non-void function を消す*/
#include    <stdio.h>
int main(void)
{
    printf("Hello world\n");
    return  0;
}

関数の返却値 return 0 を明示するとwarning: control reaches end of non-void function が消えます。(C89の時)


#include    <stdio.h>
int main(void)
{
    printf("Hello world\n");
}

C99ならばmain()関数の return 0 不要です。
gcc -std=c99 -Wall -Wextra


推奨しない熱血すぎるHello world!

#include    <stdio.h>
#include    <stdlib.h>
int main(void)
{
    int ret = printf("Hello world\n");
    if(ret)
        return  EXIT_SUCCESS;//成功の時
    else
        return  EXIT_FAILURE;//失敗の時
}

以下の熱血な人は多いですが、
頑張り過ぎてビジネスチャンスを逃さないようにしましょう。

(1) 関数返却値は必ずチェックする(printfといえども)
(2) main関数末尾のreturn 0 は必ず記述する(古いコンパイラにも対応のため)
(3) return 0の0はマジックナンバーなのでマクロにする
(4) 見ればわかる事も初心者のためにコメントを書く

アンケート

1
あなたが使っているC言語の規格を教えてください