string_length_for_printf.c 605 B

12345678910111213141516171819202122
  1. /*
  2. * Convert a size_t value to int, by saturating it at INT_MAX. Useful
  3. * if you want to use the printf idiom "%.*s", where the '*' precision
  4. * specifier expects an int in the variadic argument list, but what
  5. * you have is not an int but a size_t. This method of converting to
  6. * int will at least do something _safe_ with overlong values, even if
  7. * (due to the limitation of printf itself) the whole string still
  8. * won't be printed.
  9. */
  10. #include <limits.h>
  11. #include "defs.h"
  12. #include "misc.h"
  13. int string_length_for_printf(size_t s)
  14. {
  15. if (s > INT_MAX)
  16. return INT_MAX;
  17. return s;
  18. }