I am trying to find what is the allowed limit for the number of characters to be printed by printf()
in the C standard. I only found the answer in a discussion forum, which indicates INT_MAX
.
For example, I checked the following:
#include <stdio.h>
// INT_MAX 2147483647
int main()
{
int x=3;
int y = printf("%2147483647d \n\n", x); --> Confirms INT_MAX ?
// If I change the above to 2147483648, y in set to -1
printf("y = %d\n\n", y);
return 0;
}
I wanted to ask why is printf()
limited by INT_MAX
? Can anyone point out a C standard reasoning or source code reference ?
Edit
The closest answer I found was for fprintf()
. At this link, on page 568, its mentioned (under undefined behavior):
The number of characters or wide characters transmitted by a formatted output
function (or written to an array, or that would have been written to an array) is
greater than INT_MAX.
Will the above justify for printf()
as well ?
printf
is stated to return number of characters printed or -1 in case or an error. Its return type is int
. Maximum number you can store is int
is INT_MAX
.
What happens if you try to print more characters? Then printf
cannot fulfill its contract: to return number of characters written. Standard does not says what to do when contract is impossible to fulfill, so the behavior in this case is undefined by not being defined in standard.
Well, if you print with the format specifier %d, which indicates a integer number, of course your maximum printable number would be INT_MAX. But your example is wrong. You are trying to tell it to print INT_MAX digits on a number, but that, of course, far exceeds the actual numerical value INT_MAX.
As to why your example fails, I suppose printf() stores the amount of digits to print in an integer number itself.
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