In C our options for converting numbers to strings and adding them to a string are limited to:
- Write your own function.
sprintf()to a buffer.
Either way, one will have to allocate a block of memory big enough and call an out-of-line function. The out-of-line function will have to either write to a preallocated buffer or write to a static object, requiring a copy. Both are sub-optimal.
One could manually do this the optimal way by measuring the length the numbers will require first, allocate the string, and then convert/build the string. This may be faster and more efficient but is cumbersome.
I am trying to figure out elegant semantics to achieve the above automatically. As far as I can tell an out-of-line library function is out because that would entail either a copy or guessing a maximum size. To achieve the optimal way, where no memory is wasted and no unnecessary copies are performed, there will have to be a construct that is automatically inlined.
Some languages have direct syntactic means to achieve this:
let x = 10;
let str = "x: \(x)"
However that syntax does not allow one to specify radix or minimum digits or similar conversion options.
What would be an elegant syntax for a C-style language to allow fast conversion of numbers to string?