views:

90

answers:

2

This is more of a question of curiosity but does anyone know how negative precision values are handled in C++? For example:

double pi = 3.14159265;

cout.precision(-10);
cout.setf(ios::fixed, ios::floatfield);

cout << pi << endl;

I've tried this out and using GCC and it seems that the precision value is ignored but I was curious if there is some official line on what happens in this situation.

+2  A: 

Strangely (and wrongly, IMHO) the C++ Standard specifies a signed type (streamsize) as the parameter for precision, so it won't be converted to a large number. However, the standard is silent on what a negative number might mean, if anything.

anon
A: 

I can't find any specification of this behaviour neither in C++03 nor in draft of C++0x (N3092). However, the C89 standard says

7.19.6.1 The fprintf function

A negative precision argument is taken as if the precision were omitted.

I would expect that C++ std::ostream behaviour is consistent with the C I/O printf. fprintf and related functions.

A quick test with Visual C++ 10.0 and GCC 4.4.1 suggests it to be this way and negative precision means precision omitted. And, precision omitted means a default value which is 6 places as specified in 27.5.4.1 basic_ios constructors in Table 125

mloskot