+ 1
Why does does the code differ in these two cases?
In the following code to find the largest of three distinct integers, a, b, and c, Case 1 does not work while Case 2 does work. Why is this so? Case 1: Error, symbol max not found. public int intMax(int a, int b, int c) { if (a>b){ int max = a; } else { int max = b; } if(c>max){ return c; } else{ return max; } } Case 2: Valid public int intMax(int a, int b, int c) { int max; if (a>b){ max = a; } else { max = b; } if(c>max){ return c; } else{ return max; } } Copyright Nick Parlante 2016
4 Answers
+ 10
In Case 1 the scope of the variable int max is limited to the block in which it is declared.
Here the variable max is no longer available
if(c>max){
return c;
}
else{
return max;
}
+ 7
case 1 : max has scope in the if block , later in the else block.
after the else block max is out if scope
+ 4
It is because rules of variable scoping. All local variables declared inside block of code is not visible outside of this block. So you declare int max inside "if" code block and when you get out there and check if c > max, max is already unset by that time.
+ 1
Not 100% sure, but I think it could be because you defined int max before the if sentence in the second code, but defined int max in the if sentence in the first code. So when it starts the first code it can't find max because it isn't defined