The bottom line here is that what you are trying to express cannot be possibly expressed by a single logical condition with the declaration of alpha
being embedded into it (despite what some other answers claim).
The other answers already explained to you that your condition is not parsed the way you think it is parsed, although many answers make an obvious error of referring to the precedence of =
operator in the condition, while in reality there's no =
operator there whatsoever. The correct explanation is that when you declare a variable in the if
condition, the syntax is that of declaration with an initializer, so the whole thing is parsed the same way as
int alpha = value1 - value2 && alpha > 0.001;
would be parsed, i.e. it is a declaration of int alpha
initialized with value1 - value2 && alpha > 0.001
. There's no operator =
in it. And I hope now you can see why the compiler says that you are reading an uninitialized variable in the initializer expression. The compiler would make the same complaint on the following declaration
int alpha = alpha; // reading uninitialized variable
for the very same reason.
To achieve what you are literally trying to express, you have to either pre-declare alpha
int alpha;
if ((alpha = value1 - value2) && alpha > 0.001) {
// whatever
}
or split your if
into two
if (int alpha = value1 - value2)
if (alpha > 0.001) {
// whatever
}
However, since the second condition already requires alpha
to be greater than 0
, it doesn't make much sense to even verify the first one, so the most meaningful thing to do would be to just reduce the whole thing to
int alpha = value1 - value2;
if (alpha > 0.001) {
// whatever
}
Of course, as others already noted, the comparison of an int
value to 0.001
is a valid, but rather weird thing to do. Just do
int alpha = value1 - value2;
if (alpha > 0) {
// whatever
}