0

Sorry if this seems like a stupid question. I'm sure you guys know why this happens, but in my code for (C++) for the function

int result = calculateResult(getUserInput1(), getMathematicalOperation() , getUserInput2())

The function 'getUserInput2()' is run first instead of 'getUserInput1(). Is this normal for the functions in C++ to be run backwards when imbedded withing another function?

The full code is below

// SimpleCalculator.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>

int getUserInput1()
{
    std::cout << "Please enter an integer 1: ";
    int value;
    std::cin >> value;
    return value;
}

int getUserInput2()
{
    std::cout << "Please enter an integer 2: ";
    int value;
    std::cin >> value;
    return value;
}

int getMathematicalOperation()
{
    std::cout << "Please enter the operator you wish to use (1 = +, 2 = -, 3 = *, 4 = /): ";
    int op;
    std::cin >> op;

    std::cout << "the operator number you chose is : " << std::endl << op << std::endl;

    return op;
}

int calculateResult(int x, int op, int y)
{
    if (op == 1)
        return x + y;
    if (op == 2)
        return x - y;
    if (op == 3)
        return x * y;
    if (op == 4)
        return x / y;

    return -1;
}

void printResult(int result)
{
    std::cout << "Your result is : " << result << std::endl;
}
melpomene
  • 84,125
  • 8
  • 85
  • 148

1 Answers1

3

Yes, it's normal.

Strictly speaking, the evaluation order is unspecified, and this is a common outcome of that rule.

It might seem a bit daft, but I think it's good because it really hammers home that you shouldn't rely on any particular ordering, least of all the leftmost-first ordering that you may have assumed originally.

If you need a specific evaluation order, store the call results in variables first.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    I had originally did that, but I was trying to practice by seeing how I could shorten the code and hence the above happened. It does show me that I need to be careful in assumptions. – Malan de Wet Apr 18 '16 at 15:02