Showing precision incorrectly

The following program should show the current precision. Instead it always shows 6:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>         /// cout
#include <iomanip>          /// setprecision()

using namespace std;


int main()
{
    cout << "cout.precision()="
         << cout.precision() << " : "
         << 123.456 << endl;

    cout << "cout.precision()="
         << setprecision(4)
         << cout.precision() << " : "			/// shows 6
         << 123.456 << endl;
}


https://ideone.com/BzKDuE

Why is this happening? What's the right solution?

Thanks.
Last edited on
1
2
3
4
5
6
7
8
9
   cout << "cout.precision()="
         << cout.precision() << " : "
         << 123.456 << endl;
         
         cout.precision(4);

    cout << "cout.precision()="
         << cout.precision() << " : "
         << 123.456 << endl;
> Why is this happening?

Order of evaluation.

In C++17, this will work as you expect it to work.
http://coliru.stacked-crooked.com/a/36721b9e0fe84592

This was added by C++17:
19) In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2
http://en.cppreference.com/w/cpp/language/eval_order
Side note: I think this is the perfect case study of why abusing operators is a Bad Idea.

First, we overload shift operators to do something magical.

Then we discover that the new shift-operator idiom is understood differently than every other operator, causing confusion with users.

Now, since the operator re-purposing is a major part of the language, we must go back and add special constraints to the operator -- not to fix the operator’s function, but to fix the commonly perceived use-case of that operator.

LOL.



You are not guaranteed any evaluation order for operands for any operators (except && and ||, to support their magical unoverloaded short-circuit behavior). The only guarantee is that both operands be evaluated before the operator is applied.

(There is even an entire section of the upcoming FAQ about it. http://michael-thomas-greer.com/faq/logic/#short-circuit.)
Topic archived. No new replies allowed.