if statement and scopes
A developer writes some code that includes an if statement code block. They initialize one integer variable to a value of 5 above (outside) of the code block. They initialize a second integer variable to a value of 6 on the first line inside of the code block. The Boolean expression for the code block evaluates to true if the first integer variable has a value greater than 0. On the second line inside the code block, they assign the sum of the two values to the first variable. On the first line after the code block, they write code to display the value of the first integer. What is the result when the code statement used to display the first integer is executed?
I try to write this code in my IDE to answer the question although while I'm getting an error the answer is that the program runs without errors just displays the wrong value.
Here is my code:
static void Main()
{
int x = 5;
if (x > 0)
{
int y = 6;
int x = x + y;
}
Console.Read();
}
I get the errors:
Error CS0136 A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
Use of unassigned local variable 'x'
9 Replies
on this line
saying
int
again tells C# you're declaring a new variable" they assign the sum of the two values to the first variable." doesn't this tells me to do that?
or they just x = 11?
C# won't let you redefine it, they are both accessable inside the if block.
you can reasine it in the if but not re-define
can you give me an example of reassigning please
when you say int x = x + y, don't use the int in front, just assign a new value to x like
or
oh so I can't redeclare the variable type even if its the same cause it counts as declaring the whole?
right, your trying to instantiate another variable of the same name and type
alr appreciate it
you only need specify the type on decleration