What is the maximum width value I can put in the %d
format specifier? For example:
int c=0;
printf("%1234567899d%n",0,&c);
printf("%d",c);
When I use large values the written value of c
is 0
. Why is that?
- Stack Overflow Specifying maximum printf field width for numbers (truncating if necessary)? You can truncate strings with a printf field-width specifier: Unfortunately it does not work for numbers (replacing d with x is the same): Is there an easy/trivial way to specify the number of digits to be printed even if it means truncating a number?
I learned recently that you can control the number of characters that printf will show for a string using a precision specifier (assuming your printf implementation supports this). There are two ways to approach string-limiting.
The C standard does not specify a limit; nothing is given for a limit in the fprintf specification (which also specifies printf) in C 2018 7.21.6.1. Apple Clang 11.0.0 on macOS 10.14.6 prints a lot of spaces followed by “01234567899”, so it appears to be processing the conversion specification faithfully.
int printf ( const char * format, ... ); Writes the C string pointed by format to the standard output ( stdout ). If format includes format specifiers (subsequences beginning with % ), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
Although it's not stated explicitly, the type of the field width is most likely an int
. This is because if the field width is given as *
then an int
argument is expected.
Section 7.21.6.1p5 of the C standard regarding the fprintf
function (any by extension printf
) states the following regarding field witdh:
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an
int
argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a-
flag followed by a positive field width. A neg ative precision argument is taken as if the precision were omitted.
I tested this on CentOS 7 and Ubuntu 18, and the largest width I could specify was 2147483614 which is 33 less than the max value for a signed 32 bit int
. If I use anything larger the first printf
prints nothing and c
remains 0.
Go generally speaking, the largest value you can expect for c
would be INT_MAX
, however the exact value will vary based on the implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With