1

I have this function which when I run it it gives me the wrong answer due to the scope of the variable numer. Is there a way to use only one return statement for this function. I had to separate return statement which gave me the right answer (you can see with the //).

double calc_real_root(double a, double b, double c, double disc, double operation)
{ 
  double denom=2*a;
  double numer;
  if (operation == ADD)
  {
    double numer = -b + sqrt(disc);
    //return numer / denom ;
  }

  else 
  {
    double numer = -b - sqrt(disc);
    //return numer / denom ;
  }
  return numer / denom ;
}
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
JCZ2
  • 13
  • 2
  • 1
    Don't create a new numer in a nested scope that hides the outer numer. Just use/assign to the existing numer from the outer scope, i.e. numer = ...; rather than double numer ... – Avi Berger Nov 12 '19 at 04:05
  • `operation == ADD` (which looks like `enum`) but with `double operation` :-/ – Jarod42 Nov 12 '19 at 09:28

2 Answers2

2

You've declared three variables named numer:

  1. The initial one is uninitialized and is used in the return statement
  2. The one in the body of the if
  3. The one in the body of the else

The solution is to remove the double from the if and else bodies. For example,

numer = -b + sqrt(disc);
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
1

The problem is that you are shadowing the outer variable numer with an inner variable of the same name.

See: Shadowing variables

You can assign to the variable numer from the inner scopes, instead of declaring new variables.

double calc_real_root(double a, double b, double c, double disc, double operation)
{ 
  double denom=2*a;
  double numer;
  if (operation == ADD)
  {
    // Assign to `numer` without declaring new variable.
    numer = -b + sqrt(disc);
  }
  else 
  {
    numer = -b - sqrt(disc);
  }
  return numer / denom ;
}
NicholasM
  • 4,557
  • 1
  • 20
  • 47