C
C#3mo ago
naber top

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
mg
mg3mo ago
on this line
int x = x + y;
int x = x + y;
saying int again tells C# you're declaring a new variable
naber top
naber top3mo ago
" 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?
Devin F.
Devin F.3mo ago
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
naber top
naber top3mo ago
can you give me an example of reassigning please
Devin F.
Devin F.3mo ago
when you say int x = x + y, don't use the int in front, just assign a new value to x like
x = x + y;
x = x + y;
or
x += y;
x += y;
naber top
naber top3mo ago
oh so I can't redeclare the variable type even if its the same cause it counts as declaring the whole?
Devin F.
Devin F.3mo ago
right, your trying to instantiate another variable of the same name and type
naber top
naber top3mo ago
alr appreciate it
Devin F.
Devin F.3mo ago
you only need specify the type on decleration