What's the Difference Between Printf and Printf_S in C?
I Just Want to Know the Difference and I've Already Tried Search on Google. Printf() Printf_S() 0 1 Answer I Learned Something New Today. I've Never Used the...
I just want to know the difference and I've already tried search on google.
printf() printf_s()
1 Answer
I learned something new today. I've never used the _s functions and always assumed they were vendor-supplied extensions, but they are actually defined in the language standard under Annex K, "Bounds-checking Interfaces". With respect to printf_s:
K.3.5.3.3 Theprintf_sfunctionSynopsis
1Runtime-constraints#define _ _STDC_WANT_LIB_EXT1_ _ 1 #include <stdio.h> int printf_s(const char * restrict format, ...);2
formatshall not be a null pointer. The%nspecifier394) (modified or not by flags, field width, or precision) shall not appear in the string pointed to byformat. Any argument toprintf_scorresponding to a%sspecifier shall not be a null pointer.3 If there is a runtime-constraint violation, the
printf_sfunction does not attempt to produce further output, and it is unspecified to what extentprintf_sproduced output before discovering the runtime-constraint violation.Description
4 The
printf_sfunction is equivalent to theprintffunction except for the explicit runtime-constraints listed above.Returns
5 The
printf_sfunction returns the number of characters transmitted, or a negative value if an output error, encoding error, or runtime-constraint violation occurred.
394) It is not a runtime-constraint violation for the characters%nto appear in sequence in the string pointed at by format when those characters are not a interpreted as a%nspecifier. For example, if the entire format string was%%n.
To summarize, printf_s performs additional runtime validation of its arguments not done by printf, and will not attempt to continue if any of those runtime validations fail.
The _s functions are optional, and the compiler is not required to support them. If they are supported, the macro __STDC_WANT_LIB_EXT1__ will be defined to 1, so if you want to use them you'll need to so something like
#if __STDC_WANT_LIB_EXT1__ == 1
printf_s( "%s", "This is a test\n" );
#else
printf( "%s", "This is a test\n" );
#endif