Click here to Skip to main content
15,904,823 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For some reason this runs fine on Java:
Java
public int intMax(int a, int b, int c) {
  int max;
  if (a > b) {
    max = a;
  } else {
    max = b;
  }
  if (c > max) {
    max = c;
  } 
  return max;
}

However when I try to run the following I get the error "variable output might not have been initialized":
Java
public int close10(int a, int b) {
  int output;
  if (Math.abs(a - 10) > Math.abs(b - 10)) {
    output = b;
  }
  if (Math.abs(a - 10) < Math.abs(b - 10)) {
    output = a;
  }
  if (Math.abs(a - 10) == Math.abs(b - 10)) {
    output = 0;
  }
  return output;
}

In the first example "int max" was not initialized, however, for the second one "int output" had to be initialized. I initialized it and gave it a random number (1) and it worked fine but why did I have to initialize it and not the other one?

Thanks in advance

What I have tried:

A little code here, a little code there
Posted
Updated 6-Sep-18 17:06pm
v2

Problem is: in the first snippet, max is always initialized (from the compiler's point of view) since there is an else clause. This else clause ensures that the variable will always be initialized.
There is no else clause in the second snippet. Thus, again from the compiler's point of view, there is an uninitialization made possible (even if, mathematically, one of the three conditions will necessarily be met).
 
Share this answer
 
v2
Quote:
However when I try to run the following I get the error "variable output might not have been initialized":

This is because this code is beyond the compiler understanding.
The compiler see 3 independent conditions but is unable to understand that they are complementary and 1 will do.
Because the 3 conditions are complementary, the third is overkill and the same logical result can be achieved with:
Java
public int close10(int a, int b) {
  int output;
  if (Math.abs(a - 10) > Math.abs(b - 10)) {
    output = b;
  }
  else if (Math.abs(a - 10) < Math.abs(b - 10)) {
    output = a;
  }
  else {
    output = 0;
  }
  return output;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900