I often see in C and C++ code the following convention:
some_type val;
val = something;
some_type *ptr = NULL;
ptr = &something_else;
instead of
some_type val = something;
some_type *ptr = &something_else;
I initially assumed that this was a habit left over from the days when you had to declare all local variables at the top of the scope. But I've learned not to dismiss so quickly the habits of veteran developers. So, is there a good reason for declaring in one line, and assigning afterwards?
Best Answer
C
In C89 all declarations had to be be at the beginning of a scope (
{ ... }
), but this requirement was dropped quickly (first with compiler extensions and later with the standard).C++
These examples are not the same.
some_type val = something;
calls the copy constructor whileval = something;
calls the default constructor and then theoperator=
function. This difference is often critical.Habits
Some people prefer to first declare variables and later define them, in the case they are reformatting their code later with the declarations in one spot and the definition in an other.
About the pointers, some people just have the habit to initialize every pointer to
NULL
ornullptr
, no matter what they do with that pointer.