Search code examples
c++arraysuninitialized-constant

Uninitialized variable trouble C++


I keep getting the error message that "'rate' is uninitialized in this function".

Can anyone off the bat see why? I've looked through my code and I'm passing it correctly on my other functions, and the error stems from this function. Any ideas?

double compute_rate(int userAge_array[], char sportType_array[], int index)
{
  double rate;
  if (sportType_array[index] == 'f') {
    if (userAge_array[index] < 25) {
      rate = 68.95;
    }
    else if (userAge_array[index] > 25) {
      rate = 55.95;
    }
  }
  if (sportType_array[index] == 'g') {
    if (userAge_array[index] < 25) {
      rate = 73.95;
    }
    else if (userAge_array[index] > 25) {
      rate = 65.95;
    }
  }
  if (sportType_array[index] == 'h') {
    if (userAge_array[index] < 25) {
      rate = 99.95;
    }
    else if (userAge_array[index] > 25) {
      rate = 92.95;
    }
  }

  return rate;
}

Solution

  • You are returning rate at the end of the function but it may never initialized because all assignments are inside ifs statements which may not be processed at all.

    Solution:

    assign it at first using some default value that you will accept in case no one of the ifs works:

    double rate=0.0;