Forum Moderators: open

Message Too Old, No Replies

Visual Studio 2003 - local variables 'out of scope'

Any reason why some of my variables are out of scope when debugging?

         

bhonda

9:44 am on Apr 12, 2010 (gmt 0)

10+ Year Member



Hey guys,

I'm having a problem. And I can't figure this one out.

It's quite simple. I am in a Visual Studio 2003 web application project. I am in a method. Inside an if statement, I declare a local variable. I give it a value. When debugging, if I put a watch on this variable after it has been asigned, I get a little error -

error: identifier 'i' out of scope

My code is something like this -

string k = "";
if (ready == true)
{
int i = 1234;
k = i + " cabbages";
}

What's really odd, is that the variable k will be absolutely fine. But i, after it has been assigned, is apparently 'out of scope'. What's strange, is that k is assigned '1234 cabbages' correctly. So the value is correct, just debugging is not.

I've been doing this for a while, but I just don't get it.

I've rebuilt, I've made sure that the 'Optimise Code' is set to false.

What else can I do?

Cheers,

B

marcel

11:47 am on Apr 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can best declare 'i' outside of the if block, ie:
int i;
string k = "";
if (ready == true)
{
i = 1234;
k = i + " cabbages";
}


In your example i only exists within the scope of the if block, any code outside of this block (and also the debugger) does not know of the existence of i.

bhonda

12:09 pm on Apr 12, 2010 (gmt 0)

10+ Year Member



Hey,

Thanks for this, but my problem is slightly different - even within the if block, after i has been declared and assigned, the debugger cannot see it. Another instance where this is a problem is if I use a for or foreach loop - the code functions, but I cannot investigate what's going on.

Cheers,

B

Ocean10000

1:43 pm on Apr 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



"i" is only set if "ready" equals true, so if "ready" equals false "i" will never be set".

bhonda

2:10 pm on Apr 12, 2010 (gmt 0)

10+ Year Member



Hey,

Thanks for the reply.

I think I'm explaining myself badly though!

If ready is true, and I set a breakpoint on -

k = i + " cabbages";


Then surely I should be able to investigate the value of i?

This isn't really a problem of flow - it's a problem with the debugger not being able to see local variables. I know this line is being called, and the actual result is as expected, it's just when I'm stepping through it line-by-line, I cannot investigate the values - even though I should be able to!

Is there some setting for the debugger that defines it's perspective? Is there any reason why the debugger would not be able to see any variables defined within the if block, if the current focus is on a line in the if block as well?

Cheers,

B