Click here to Skip to main content
14,241,186 members
Rate this:
Please Sign up or sign in to vote.
See more:
For some reason this runs fine on 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":
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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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).
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

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:
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;
}
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100