share
Stack OverflowWhy declare a variable in one line, and assign to it in the next?
[+44] [0] Jonathan Sterling
[2011-05-07 20:30:03]
[ c++ c declaration assignment local-variables ]
[ http://stackoverflow.com/questions/5923793] [DELETED]

(I figured this question was already asked, and searched for it, but was unable to find a duplicate; if I missed something, please delete this one and accept my apologies!)

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?

EDIT: Some people are confused about my tagging of this question as both c and c++. So, to clarify, I was interested in the difference between how these will behave in both C and C++. There are a lot of instances where the same code will behave differently in C++ than in C.

EDIT 2: Apologies for the poor wording: I probably shouldn't have used the words declare and define without making clear exactly what I meant by them, since they have very specific meanings in different contexts. I've changed the title to say “assign” instead.