itoa and C++11 std::string

Stefan Heinzmann
Mon Dec 15 13:12:00 GMT 2014

I noticed the itoa thread from a week ago, which plays along nicely with my own problem/suggestion.
I noticed that in stdlibc++, std::to_string is implemented in terms of vsnprintf. This follows the semantics of the C++11 standard, but is inefficient. It would be better to implement std::to_string in terms of dedicated itoa-like functions, if they were available. This would be particularly desirable in embedded systems, where you don't want the whole printf code instantiated just for printing an integer.
Of course, stdlibc++ implements it in terms of vsnprintf, because there are no standard itoa functions it can build on. If you have only what the C99 standard offers, you have no choice but going through printf and its cousins, unless you want to reimplement the functionality from scratch.
If some consensus could be reached between newlib and stdlibc++, and perhaps other C libraries, about the signature and semantics of itoa functions in the C library, the C++ library could be made to use them profitably. itoa and utoa as proposed a week ago would not suffice, however, because long long and unsigned long long have to be catered for, too. In fact, it would probably suffice to just provide the functions for the largest integer types, because the other types can easily be converted. The somewhat unsafe interface of the original itoa would not be a problem here, because stdlibc++ can easily make sure the function is called with safe arguments. Even the check for a valid number base could be omitted IMHO.
The floating point numbers pose a similar problem, which can be solved using the ecvt-family of functions (which have been obsoleted by POSIX, but not ANSI C).
To make matters worse, stdlibc++ omits the std::to_string functions when there's no complete C99 support, which means that they are not available when stdlibc++ is used with newlib, even though newlib has everything that is needed. They appear to wait for newlib, although I'm not sure what exactly it is they're waiting for.
In a nutshell, what I propose is to change the proposed itoa/utoa implementation of last week in the following way:
-- Use the largest available integer type
-- Omit for efficiency: The validity check for base
-- Use a function name with two leading underscores
-- If desired, implement the more traditional function signatures as a wrapper around the new functions
-- Try to agree this with the glibc and the stdlibc++, and provide a feature test macro for it.
Does this appear reasonable?

More information about the Newlib mailing list