Does variable declaration mean memory allocation?

后端 未结 5 1135
旧时难觅i
旧时难觅i 2020-12-29 07:05

Will it be precise to say that in

void f() {
    int x;
    ...
}

\"int x;\" means allocating sizeof(int) bytes o

5条回答
  •  無奈伤痛
    2020-12-29 07:56

    I think it depends on compiler. I used the default compiler for Code::Blocks and Dev-C++ and it looks like memory is allocated during initialization. In following cout statement, changing n2 to n1 will give the same answer. But if I initialize n1 to some value, or if I display n2 before I display the average, I will get a different answer which it is garbage. Note that VS does correctly handles this by giving error since variables are not initialized.

    void getNums();
    void getAverage();
    
    int main()
    {
        getNums();
        getAverage();
    
        return 0;
    }
    void getNums()
    {
        int num1 = 4;
        double total = 10;
    }
    void getAverage()
    {
        int counter;
        double n1 , n2;
        cout << n2/counter << endl;
    }
    

提交回复
热议问题