Periodically, I bump into unusual behavior, features, of compiler, operating system, strange design and coding decisions made by someone else that makes me wonder. After giving it some thought, I often come to the conclusion that behavior or observed specifics are justifiable. However if I knew it upfront, It would have helped me to avoid unnecessary mistakes and complexity.
Today I would like to open new section in my blog: Be Aware. In this section I would like to spend some time on this exact subject: strange behaviors and unexpected features. Sometimes these type of things are fascinating, sometimes just interesting and sometimes are just naïve. My goal is to point them out so that when you make your own decisions you will have more information to rely on. My goal is not to uncover bugs or start some kind of religious debates – I really don’t like them. I strongly believe that problem drives a solution. What I mean by this is that something outrages in one place will be fully applicable in the other.
So let’s begin :-).
The topic of variable’s placement have been covered to full extend by now. Some developers prefer to declare all variables upfront some in the scope where variables get actually used. Personally, I have heard cons and pros for both sides and kind of agree with both. I think there is no black and white. In some cases you do have to declare a variable inside of the given scope. Recently I have observed interesting debugger’s behavior while debugging dumps. As all of you know debugger usually has difficulties to show local variables for retail, optimized build. This is kind of expected in many cases. Before you can rely on a value, you have to confirm that the value is really correct. In windbg I usually use dv command to output local variables
> dv -V
Using the command with -V lists the actual placement of the variable on the stack. What I noticed is that windbg wasn’t displaying variables declared in local scopes at all even if instruction pointer was inside of the scope. It just doesn’t list them! So I usually end up chasing those variables by disassembling the code and following stack manipulations. (Knowing original stack assignment in this cases would really helped) The process works 100% of the time, but I would have saved hours if the code declared variables in the beginning of the function. At least the debugger would gave me a clue where the variable resides on the stack.
Probably the point here is that avoiding unnecessary complexity could enable tools to do better job and make everyone life easier. Remember tools, as any software, well tested for the common case. So next time when declaring a variable in an internal scope just stop for a second and think: Is it really necessary?
I have more stories around complexity but I will keep them until next time :-).