Variable Declaration & Initialization :: C++

Status
You're currently viewing only Liam's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

Liam

Ars Scholae Palatinae
618
Kuphryn, to answer your initial question: I agree with those who have mentioned that declaring your variables at the very beginning of your function helps you think about their necessity. I also agree with those who would caution you to delay the variable declaration until you can initialize it with something specific (I am a very agreeable person!). I therefore tend to use the following guidelines: if a variable's _intended lifetime_ (not necissarily the scope) extends for the entire function, or if it is used in several places not immediately next to each other, declare it at the top. In this way, the declaration can be guaranteed not to be lost amongst code. If a variable's intended lifetime is very short (e.g. a loop index), declare it only right when you need it. This saves you from seeing "int i,j,k" at the top of your function; they don't really become relavent until you actually get to the loops.

Above all else, be aware of the scope of your variables, and the use of constructors when instantiating classes. Perhaps, as mentioned, you don't want to call the default constructor (or there isn't one available). In this case, feel free to delay your declaration until you have something to initialize it with, even if this violates guideline #1. I'm definitely a member of the "there are no hard-and-fast rules" school of programming style, but it's certainly nice to have guidelines.

Just my personal coding preference. Some of you may be glad you don't have to maintain my code, because I'm some kind of freak who doensn't like Hungarian letters hanging off my variable names and doesn't declare all his variables in one place.
 
Status
You're currently viewing only Liam's posts. Click here to go back to viewing the entire thread.
Not open for further replies.