It's because you are declaring the variables in an if
statement.
Logically you may be of the belief that the else
in a way guarantees that the variables will be assigned if the declaration is in both the if
and also in the else
block.
The correct way to do it is to just declare the variables before the if
block, otherwise the variables use will be restricted to the scope from which it was declared.
Also, you can do this without the need for an if
and else
by using ternary operations:
int a = 1;
int b = 2;
int c = a >= b ? a : b;
int d = b < a ? b : a;
With this type of syntax, you can save yourself the hassle of writing if
and else
blocks for simple variable assignments. The variable after the ?
is the result if the condition is true, and the variable after the :
is the result if the condition is false.