LoginSignup
3
4

More than 5 years have passed since last update.

関数内のstatic変数が初期化するのはその行が実行されるとき

Last updated at Posted at 2014-12-21

以下の内容は間違ってる部分があります、正しくはコメントを参考してください。


当たり前だけと多くのサイトでは誤解しやすいように書かれています、
関数内のstatic変数はプログラムが実行されるときではなく関数が実行されるときでもはく
その行が実行されるときに初期化されます。

テストコード

#include <iostream>

int static_int(int value) {
    std::cout << "create " << value << std::endl;
    return value;
}

void hoge(int i) {
    std::cout << "call hoge" << std::endl;
    if (i >= 0) {
        std::cout << "if i positive" << std::endl;
        static int ii = static_int(i);
        std::cout << ii << std::endl;
    } else {
        std::cout << "if i negative" << std::endl;
        static int ii = static_int(i);
        std::cout << ii << std::endl;
    }
}

int main() {
    hoge(1);
    hoge(2);
    std::cout << "---" << std::endl;
    hoge(-1);
    hoge(-2);
    return 0;
}

実行結果

call hoge
if i positive
create 1
1
call hoge
if i positive
1
---
call hoge
if i negative
create -1
-1
call hoge
if i negative
-1
  • 実行結果から分かること

    • static変数はその行が実行されるときに初期化されます
    • static変数の初期化に普通の変数を使えます(実際に使うのは控えてください)
    • static変数の初期化は一回しかしません(マルチスレッドでなければ)

基本的にstatic変数を一回目の実行結果を保存して二回目以降で使う変数だと思えばいいでしょ。

マルチスレッドの場合はコンパイラによっては一回以上初期化されることがあります、
上記の例ではstatic_int関数が複数回実行され、iiは最後に実行した回の結果になります。
詳しくはthreadsafe-staticsを検索してください。

3
4
2

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
3
4