-2

I'm stumped on why the line:

cout << "Your average in this course is " << average() << " and your letter grade is " << convert_to_letterGrade() << "\n";

does not work, whereas the following works (one cout is split into 2):

cout << "Your average in this course is " << average();
cout << << " and your letter grade is " << convert_to_letterGrade() << "\n";

This code is in a void function that is a public member of the class Grades. average() calculates and stores the result in the private member variable averageScore, and also returns averageScore. convert_to_letterGrade() returns a char value based on the value of averageScore and an error message if the average score is not reasonable, and both functions are private members of the class.

In the first case, I get the error message from convert_to_letterGrade() first, THEN followed by what the cout statement was supposed to print. The cout statement prints the correct averageScore value, but when I stepped into convert_to_letterGrade(), the function was still using a garbage value for averageScore, whereas the second one works perfectly fine and convert_to_letterGrade() is also using the correct averageScore value.

Why is this?

Keith Thompson
  • 230,326
  • 38
  • 368
  • 578
ruisen
  • 175
  • 2
  • 11

2 Answers2

5

convert_to_letterGrade() returns a char value based on the value of averageScore and an error message if the average score is not reasonable

Based on your description of the behavior, this is not actually true.

Your current function returns a char value if the score is reasonable, or prints an error message directly to cout if unreasonable.

Fixing it is as simple as doing what you said, making the error string a return value so that the caller controls when it gets printed.

In addition to that, you have the problem of convert_to_letterGrade() relying on the variable set by the other function. As gnasher729 mentions in his answer, there is no guarantee that average() gets called before convert_to_letterGrade() unless you put a sequence point in between.

Ben Voigt
  • 260,885
  • 36
  • 380
  • 671
5

You should be aware that functions within an expression can be called in any order.

I would assume that your implementation of convert_to_letterGrade depends on average() being called first, and that isn't guaranteed in your first statement.

Writing a function that only gives a correct result if another function has been called before is a dangerous practice. What would happen if I only wanted to print the grade as a letter? Would I have to remember to call average () first? That is an awful practice. Or what if you wanted to print the letter score first, followed by the average?

gnasher729
  • 47,695
  • 5
  • 65
  • 91