- Is my interpretation of the standards somehow wrong?
I interpret your interpretation as follows:
So printf("%.-1s\n", "foo") should be equivalent to printf("%s\n", "foo") , which displays "foo\n" and returns 4.
Not. Your statement on ignored negative precision arguments does not apply to this case. This statement indicates the possibility of specifying precision as * in the format string and passing the value as a separate printf argument:
printf("%.*s\n", -1, "foo");
In this case, the negative precision argument causes printf() behave as if precision were not specified. Your case is different.
On the other hand, the standard here does not require that the precision value displayed in the format string be a non-negative decimal integer. He really qualifies the term βdecimal integerβ in this way in several other places, including in the same section, but this is not done in the paragraph on the precision field.
- Is this behavior undefined?
Not. There are two conflicting interpretations of the required semantics (see next), but in any case, the standard defines behavior. It can be interpreted as
the behavior described for the negative precision argument also applies when a negative precision value is represented directly in the format string. This has the advantage of consistency, and this is the behavior you report. Nevertheless,
a literal reading of the standard indicates that when precision is represented as a negative decimal integer in a format string, then the usual semantics described in this section apply; for s directives, this means that negative precision expresses the maximum number of characters that will be output.
The behavior that you observe is incompatible with the previous interpretation, but given the practical difficulties in outputting less than 0 bytes, it seems to me a little surprise that the latter interpretation was not successfully implemented. I am inclined to assume that the latter is what your implementation is trying to implement.
I suspect that at some stage there was an unintentional omission in order to leave the opportunity to give a negative value for the accuracy field, but intentionally or not, the standard seems to allow this.
John bollinger
source share