What is printf_s in C?

What it does

printf_s is a function in the C library. Like the printf function, the printf_s also prints given arguments into the standard output stream, but it has the added functionality of validating these arguments before they are printed. These validation checks take place at run time. If any them fail, the execution ceases.

Function syntax

Parameters

The restrict format string contains specifications like %s and %n that determine the output format of the arguments to print.

Return value

printf_s returns a negative value if there is an error in execution or if any run time checks fail. Otherwise, it returns the number of characters transmitted to the output stream for successful execution.

The printf_s function is optional and not all compilers support it. If it is supported, the macro STDC_WANT_LIB_EXT1 will be defined to 1.

Runtime checks

printf_s performs the following checks at run time on the argument it receives:

  • The format is not a null pointer.
  • The %n specifier is not present inside the string pointed to by the format argument.
  • The argument corresponding to a %s specifier present in the format does not point to null.

Example

Since printf_s function’s compiler support is optional, your code must always accommodate both potential options. This is done by only invoking printf_s when the macro STDC_WANT_LIB_EXT1 is set to 1.

if __STDC_WANT_LIB_EXT1__ == 1
printf_s( "%s", "print_s works\n" );
else
printf( "%s", "print_s not supported\n" );

Output in the case printf_s is supported:

print_s works

Output in the case printf_s is not supported:

print_s not supported

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved