-6

I've tried Googling and actually searching this website for a concise answer on this and so far I have been unable to find some help, I believe it might be because the answer is too simple.

I have just started uni and we have some exercises to resolve. In one of them I am presented with the following:

float avge(int a, int b, int c) {
  float res;
  res = (a + b + c) / 3.0;
  return res;
}

int main() {
  int n1, n2, n3;
  float m;
  cin >> n1;
  cin >> n2;
  cin >> n3;
  m = avge(n1, n2, n3);
  cout << m << endl;
  return 0;
}

It works as intended but I can't understand what res does for the code. Could someone explain it to me?

Biffen
  • 6,249
  • 6
  • 28
  • 36
33X
  • 15
  • 1
  • 1
  • 3
  • 2
    its the name of a variable (presumably short for `result`), you could change it to `foo` and your program would still work in the same way – Alan Birtles Sep 14 '18 at 11:02
  • 8
    1) It is a variable declared in a statement `float res;` What exactly, about it, is unclear for you? 2) This should be explained in the lectures, in your university. Alternatively, you can learn from one of [these C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius Sep 14 '18 at 11:02
  • Ignore this if it seems confusing. In general, try to initialize variables when they are created, rather than create them and initialize them later. This code (not yours, I know, just giving unsolicited advice) should be `float res = (a + b + c) / 3.0;` instead of `float res; res = (a + b + c) / 3.0;`. It's not wrong as written, but it's a bad habit. – Pete Becker Sep 14 '18 at 11:57

1 Answers1

3

res is the name of a local variable in the function avge that is returned at then end of that function.

// Variable of type float with name "res" is declared
float res;

// Compute some value and assign it to this variable
res = (a+b+c)/3.0;

// Return the variable to the caller
return res;

"res" usually is an abbreviation for "result".

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • Thank you that makes sense. These are exercises in preparation for the class in which this will be explained and I was simply trying to make sense of it. – 33X Sep 14 '18 at 11:16