4
$\begingroup$

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?

$\endgroup$

1 Answer 1

3
$\begingroup$

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

In Swift (which uses the exact syntax you used in the question), it actually does. It's not a built-in overload, but \(...) compiles to a method call, and you can add your own overloads for it:

extension DefaultStringInterpolation {
  mutating func appendInterpolation<T: BinaryInteger>(_ x: T, radix: Int) {
    self.appendInterpolation(String(x, radix: radix))
  }
}

print("Hello, \(24, radix: 8)")

SwiftFiddle Link

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .