Hasty Briefsbeta

Generalizing Printf in C

3 days ago
  • #ANSI C89
  • #Function Pointers
  • #C Programming
  • ANSI C89 includes 6 printf functions: printf, sprintf, fprintf, vprintf, vsprintf, vfprintf.
  • Other C versions add more printf functions like dprintf, snprintf, asprintf, vdprintf, vsnprintf, vasprintf.
  • The difference between these functions lies in input format and output source.
  • Proposal to generalize printf functions into one core function to reduce redundancy.
  • Simple optimizations can reduce the number of functions needed from 12 to 4.
  • sprintf is discouraged due to security risks, similar to gets.
  • Three key functions remain: vfprintf, vasprintf, vsnprintf.
  • Generalizing these into one function is possible but inefficient due to memory usage.
  • Discussion on qsort in C89, highlighting its use of function pointers and type transmutation.
  • Example of qsort usage with different array types and the lack of type safety.
  • Proposal for a printf implementation using function pointers and state management.
  • Introduction of a struct bufinfo to manage state during buffer writing.
  • Example implementation of vsnprintf using state management.
  • Alternative solutions and considerations for future C standards.