I have this problem with my functions.
in the main function I have this result(param, param)
function which takes 2 functions as parameters.
result(name(), score());
However when the code executes the score()
function executes first and not the name()
function. why does that happen.
(Also another problem that arises from the score() function executing first and not the name()
function is that I get the \n
read and the name()
function is skipped altogether. However I know how to fix that I just need to know why isn't the name()
function executed first. ).
I found this here: http://en.cppreference.com/w/cpp/language/eval_order.
Order of evaluation of the operands of any C++ operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below). The compiler will evaluate them in any order, and may choose another order when the same expression is evaluated again.
There is no concept of left-to-right or right-to-left evaluation in C++, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression
f1() + f2() + f3()
is parsed as(f1() + f2()) + f3()
due to left-to-right associativity of operator+, but the function call to f3 may be evaluated first, last, or betweenf1()
orf2()
at run time.**
But my program always executes the score()
function first. And above it states that it is random so I should at least have the name()
function executed first sometimes right?
Full code is here for reference.
#include <iostream>
#include <string>
using namespace std;
string name()
{
string fname;
cout << "Please type your full name: ";
getline(cin, fname);
return fname;
}
int score()
{
int points;
cout << "Please type your score: ";
cin >> points;
return points;
}
void result(string fname, int points)
{
cout << "Ok " << fname << ", your score of " << points << " is ";
if (points > 100)
{
cout << "Impossible";
}
else if (points == 100)
{
cout << "Perfect!!!";
}
else if (points >= 85 && points < 100)
{
cout << "Amazing!!";
}
else if (points >= 70 && points < 85)
{
cout << "Good!";
}
else if (points >= 50 && points < 70)
{
cout << "Ok.";
}
else if (points < 50)
{
cout << "Bad...";
}
else
{
cout << "Incorrect input";
}
}
int main()
{
result(name(), score());
return 0;
}