Why separate variable definition and initialization in C++?

前端 未结 8 1529
心在旅途
心在旅途 2021-02-18 15:22

I\'m currently working on some quite old C++ code and often find things like

int i;
i = 42;

or

Object* someObject = NULL;
someO         


        
8条回答
  •  眼角桃花
    2021-02-18 16:04

    In C, there is the restriction that you have to define your variables at the top of the code block, even if you only need them somewhere later on in the function. So in the old days of C, people often first defined all their variables and then later though about the values they should have.

    Since you say it is quite old C++ code, it might use that same convention as a holdover from C practices.

    There is no real reason to do this in C++, though. Better always define your variables where you can initialize them directly.

提交回复
热议问题