Most of us who have used C++ for a while have crossed path with sprintf once or twice. It comes in handy in a variety of places. There are all the standard things you can do with %d, %s, %f and even diving into precision with %.2f to write two decimal places of precision to the output. Recently I came across a shortcut formatting token .* which I was not previously familiar with. Here is a short example of how it works and where it could be applied to IPlug.
IParam::GetDisplayForHost has the following code:
char fmt; sprintf(fmt, "%%.%df", mDisplayPrecision); sprintf(rDisplay, fmt, displayValue);
- Line 131: Creates a local buffer to hold the format string. The buffer can hold 16 characters.
- Line 132: Fills the buffer with a dynamically generated format string. % is the standard sprintf control delimiter so the %% prints a % directly into the string. %d prints an integer type and the f in this case is a plain text part of the string. If mDisplayPrecision contained the numeral 3 then fmt would be left containing the string “%.3f” which is recognizable as a format string to sprintf to print a floating point type to three decimal places of precision.
- Line 133: Uses the dynamically generated format string in fmt to place the display value into the rDisplay parameter.
Overall this is a very reasonable way to approach the problem of formatting a floating point type to a dynamically determined precision. It is how I would have traditionally approached the problem. However, I picked up a little C++ wisdom from a fellow VST plugin developer in this thread at the Cockos forum. It turns out the implementers of sprintf already anticipated this need and built a macro right into the function. The three lines of code above can be boiled down into one line.
sprintf(rDisplay, "%.*f", mDisplayPrecision, displayValue);
The .* says to use the number of precision digits to be given immediately before the value to format. This means the format string “%.*f” says we will give an integer specifying the number of digits of precision right before we give the float to format.
This is fairly basic functionality of the sprintf function but I have never encountered it before in almost a decade of C++ coding. Don’t feel embarrassed if you didn’t know this trick either. It is quite likely the Cockos engineer who wrote this code didn’t know this trick either. Coding is a lifelong pursuit of educating yourself in additional techniques. Given the number of times you are likely to be turning floats and doubles into strings for display while developing your VST plugin makes this a pretty valuable tool to put in your coding toolbox. Have fun making your next VST plugin!