Defined in carb/extras/StringSafe.h


Formats a string as if by vsnprintf and invokes a callable with the result and the length.

This macro constructs a va_list, gathers the variadic parameters with va_start, formats the string with std::vsnprintf, and calls a Callable with the formatted string and length. This function reserves a stack buffer of the size requested by size for CARB_FORMATTED_N_SIZE or a default size for CARB_FORMATTED_N, but if the formatted string will not fit into the stack buffer, will use the heap to create a larger buffer.


This macro is intended to be used in variadic functions as a simple means of replacing uses of std::vsnprintf.

void myLogFunction(const char* fmt, ...) {
    CARB_FORMATTED_N([&](const char* p, size_t len) {
        log(p, len);

  • fmt – The printf-style format string.

  • ... – A Callable that may be invoked as via ...(p, n) (where p is a const char* and n is a size_t), such as a lambda, functor or function pointer. Retaining and reading p after the Callable returns is undefined behavior. If an error occurs with std::vsnprintf then p will be <vsnprintf failed>, or if a heap buffer was required and allocation failed, then p will be <failed to allocate>. If you do not need the length provided to the Callable, use CARB_FORMATTED() or CARB_FORMATTED_SIZE() instead.