0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

static変数の性質をかんたんに理解する

Posted at

はじめに

static変数の性質が簡単に理解できるよう、以下のコードを記述しました。
コード下のwandboxからどなたでも実行結果の確認が可能です。

static_test.c
#include <stdio.h>

int num_chars(char *str)
{
    static int num_chars;

    while (*str)
    {
        str++;
        num_chars++;
    }
    return (num_chars);
}

int main(void)
{
    char    *str1 = "hello";
    
    printf("%s has %d chars.\n", str1, num_chars(str1));
    
    printf("%s has %d chars.\n", str1, num_chars(str1));
    
    return (0);
}

staic変数の2つの性質

【暗黙的に0で初期化される】
 一般的な変数は初期化を明示的に行う必要がありますが、static変数は0で初期化されます。このとき、初期化はプログラム中の最初の宣言時のみ実行されます。

【プログラムの実行中、値が保持され続ける】
 ローカル変数(宣言された関数内のみが寿命の変数)であれば一度の関数呼び出しが終了した時点で値が初期化されますが、static変数の場合、プログラム全体の実行中値が保持され続けます。
 今回の例では、一度目のnum_chars関数の呼び出しあとにnum_chars変数の中身が残っており、2回目の呼び出しの際に更に加算されることで本来5文字を期待したい戻り値が10文字になっています。

終わりに

取り組んだ学校の課題で学んだ内容をシンプルにアウトプットしました。なにかの参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?