Convert integer to string
Assuming we want to use the standard library, we have three options for converting an integer to a string. The exact names of the parameters may vary based on your C library - I've changed them to be clearer, e.g. destination
instead of buf
(the order is the same).
Standard | Function |
---|---|
C89 | sprintf(char * restrict destination, const char * restrict format, ...) |
C99 | snprintf(char * restrict destination, size_t maximum_length, const char * restrict format, ...) |
C11 | snprintf_s(char * restrict destination, rsize_t maximum_length, const char * restrict format, ...) |
The parameters are used as follows:
Name | Usage |
---|---|
destination |
The string generated by the function will be saved in the memory location referred to by this pointer. |
maximum_length |
The maximum number of characters that can be written to the destination. If the number of characters exceeds this, the string will be truncated at maximum_length characters (including the terminating null character), so 12345 with a maximum length of 4 will be '123'. |
format |
Format string, including placeholders marked with % . If we are converting an int , the format string will be: "%d" . |
... |
A variable number (including zero) of values for the placeholders in format . The number and order of the values must match the placeholders exactly. |
The return value is the number of characters that were written (sprintf
) or would have been written (snprintf
, snprintf_s
), i.e. the length of the string.
The difference between snprintf
and snprintf_s
is that snprintf_s
comes with additional checks at runtime, e.g. to prevent null pointers being passed as destination
and format
.
Which function to use depends on the following scenarios:
Scenario | Function | Rationale |
---|---|---|
Must support C89 / maximum portability | sprintf |
sprintf is included in the C89 standard library, the other functions are not. |
Any standard from C99 onwards | snprintf |
snprintf comes with an extra check for the maximum length, which can help reduce the likelihood of buffer overflows - although it requires the programmer to pass the correct maximum length for the destination. |
snprintf_s
is not listed in the scenarios because many implementations of the standard library do not include it (they are not required to, as it is optional and defined in Annex K of C11).