1

So i was just writing a simple calculator using functions and i wanted to be as easy used as possible. I basically wanted it that in 1 line of code you could do the whole process of asking numbers and the calculation and also calculating the result. but i have i problem. In the code down below, when i do in the main function "cout << calculate(askCalculation(), askNumber1(), askNumber2()) << endl;" and i run the program then i want it to first ask the calculation, then the first number and then the second number. But it does not do that, in fact it does it in the excact opposit way. is there a reason why, and how can i fix this?

oh and pls i know you could just put the 3 ask funtion in 1 class to make it even more simple, but is there a way i can put the calculate funtion in that same class?

#include <iostream>

using namespace std;

int calculate(int calculation, int firstNumber, int lastNumber)
{
    switch(calculation)
    {
    case 1:
        return firstNumber + lastNumber;
        break;
    case 2:
        return firstNumber - lastNumber;
        break;
    case 3:
        return firstNumber * lastNumber;
        break;
    case 4:
        return firstNumber / lastNumber;
        break;
    }
}
int askNumber1()
{
    int a;
    cout << "Give the first number" << endl;
    cin >> a;
    return a;
}
    int askNumber2()
{
    int b;
    cout << "Give the second number" << endl;
    cin >> b;
    return b;
}
int askCalculation()
{
    int c;
    cout << "what calculation do you want to do? add (1) subtract (2) multiplication (3) divide (4)" << endl;
    cin >> c;
    return c;
}
int main()
{
    cout << calculate(askCalculation(), askNumber1(), askNumber2()) << endl;
    return 0;
}

1 Answers1

2

The order of evaluation of function parameters is not defined in C or C++. If you need a specific order, assign the return values of those functions to named variables in the order you require, and then pass those variables to the function:

int a = askCalculation();
int b = askNumber1();
int c = askNumber2();
cout << calculate( a, b, c ) << endl;