2

Ideally, some of the content of my Fahrenheit function should be placed in the main function but wanted to try something out. I asked for the user input in the Fahrenheit function and after this, I called the Fahrenheit function after the cout statement. I expected the "Your temperature..." string to display first nevertheless it asked for the input before proceeding to print the string. Why is this so?

#include <iostream>
using namespace std;
int FahrenheitConv();
int main ()
{
    cout << "Your temperature in Fahrenheit is "<< FahrenheitConv();
    return 0;
}

int FahrenheitConv()
{
    double centigrade;
    cout << "What is your temperature in centigrade: ";
    cin >> centigrade;

    double fahrenheit = (1.8) * (centigrade ) + 32;
    return fahrenheit;
}
Banana
  • 2,435
  • 7
  • 34
  • 60
Isaac Attuah
  • 119
  • 1
  • 11
  • 2
    Please take [the tour](https://stackoverflow.com/tour), read [the help page](https://stackoverflow.com/help) and have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list. Welcome to SO. – Ron Feb 14 '18 at 12:38
  • The evaluation order of function arguments is unspecified. I am sure, that there is a duplicate somewhere.. – Algirdas Preidžius Feb 14 '18 at 12:38
  • The order is unspecified, see in this [example](https://repl.it/repls/AngelicTremendousScientificcomputing), I get the string you expect printed first. – Arnav Borborah Feb 14 '18 at 12:38
  • `std::cout << x << y;` is syntactic sugar for `operator<<(operator<<(std::cout, x), y)` and as mentioned before evaluation order of the arguments of a function is unspecified. So `y` may be evaluated before `std::cout << x`. – Caninonos Feb 14 '18 at 12:43
  • 2
    Yet another good reason to keep user interaction and data processing separate. – molbdnilo Feb 14 '18 at 12:50

1 Answers1

3

According to N4296:

1.9 Program Execution [intro.execution]

[...] Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations.end note ] [...]

So you can't really expect any particular order, unless for really specific cases such as logical operators and the ternary operator, which introduce sequence points.

Community
  • 1
  • 1
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • Thanks, Arnav. I did the same thing in Dev C++ and it asked for input first. Thanks again for clarifying – Isaac Attuah Feb 14 '18 at 12:44
  • IIRC, C++17 forces on order for some things such as the `<<` operator. Do you know if I'm remembering right? – Justin Feb 14 '18 at 17:24