C/C++: static variables

static variable can only be initialized once. Compiler persist the variable till the end of the program.

Eg:

#include <iostream>

int* a = NULL;

void my_delete()
{
    static int deleted = 0;
    std::cout << "deleted = " << deleted ++ << std::endl;
    std::cout << "&deleted = " << &deleted << std::endl;
    a = &deleted;
}



int main() {
    my_delete();
    my_delete();
    my_delete();
    std::cout << "in main, a = " << a << std::endl;
    std::cout << "in main, deleted = " << *a << std::endl;
    
    std::cout << "in main, a = " << a << std::endl;
    std::cout << "in main, deleted = " << *a << std::endl;
    return 0;
}

Result:

deleted = 0
&deleted = 0x6011a4
deleted = 1
&deleted = 0x6011a4
deleted = 2
&deleted = 0x6011a4
in main, a = 0x6011a4
in main, deleted = 3
in main, a = 0x6011a4
in main, deleted = 3

End

posted @ 2021-08-03 17:49  十步一杀2017  阅读(76)  评论(0编辑  收藏  举报