Why separate variable definition and initialization in C++?

前端 未结 8 1510
心在旅途
心在旅途 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:10

    Consider the following case:

    SomeType object;
    if( whateverCondition ) {
       object = getObjectOneWay();
    } else {
       object = getObjectAnotherWay();
    }
    

    this way it's clear that both branches assign the variable and its initial value is irrelevant. It's rarely worth that however.

提交回复
热议问题