+ 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

9th May 2017, 7:39 PM
Kaien Yang
Kaien Yang - avatar
4 ответов
+ 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; }
9th May 2017, 7:51 PM
Alexey
Alexey - avatar
+ 7
case 1 : max has scope in the if block , later in the else block. after the else block max is out if scope
9th May 2017, 11:19 PM
NimWing Yuan
NimWing Yuan - avatar
+ 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.
9th May 2017, 7:53 PM
Jeth
Jeth - avatar
+ 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
9th May 2017, 7:49 PM
Maart
Maart - avatar