I'm well on my way on a programming language I've written in Java that compiles directly into C99 code. I want to add string interpolation functionality and am not sure what the resulting C code would be. In Ruby, you can interpolate strings: puts "Hello #{name}!"
What would be the equivalent in C?

- 133
- 8
-
What do u mean by interpolate ? – Nutan Jan 26 '16 at 07:10
-
`printf("Hello %s!", name);` where `name` is a string, eg: `char name[] = "John";` – LPs Jan 26 '16 at 07:11
-
`printf("Hello %s!", name)`? Or are you looking for a general output system where the interpolated string can be biult at runtime and where you can print user-defined types? – M Oehm Jan 26 '16 at 07:11
-
Looking for something in general. so that it could work in variables as it also does in ruby: `@greeting = "Hello #{name}!"` – Danilo Lekovic Jan 26 '16 at 07:31
-
If you want to use literals, then you could find a macro based solution. If you need to concat string vars you must do it by code, as suggested. Take a look [HERE](http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c) – LPs Jan 26 '16 at 08:01
2 Answers
So called interpolated strings are really just expressions in disguise, consisting of string concatenation of the various parts of the string content, alternating string literal fragments with interpolated subexpressions converted to string values.
The interpolated string
"Hello #{name}!"
is equivalent to
concatenate(concatenate("Hello",toString(name)),"!")
The generalization to more complicated interpolated strings should be obvious.
You can compile it to the equivalent of this in C. You will need a big library of type-specific toString operations to match the types in your language. User defined types will be fun.
You may be able to implement special cases of this using "sprintf", which is the string-building version of C's "printf" library function, in cases where the types of the interpolated expressions match the limited set of types that printf format strings can handle (e.g., native ints and floats).

- 93,541
- 22
- 172
- 341
The printf family would be good to read, as is the scanf family of functions in the C library.

- 33,938
- 5
- 80
- 91