News for hackers. Stuff that matters.
Re:Accidentally Overwriting Another Local Variable in C and C++ by monocasa on Thursday December 05, 2019 @06:39PM (#21717883)
At least for printf, there's normally a way to tell the compiler that it's a printf style interface and get something approaching typesafety back. On gcc this is

  extern int
  my_printf (void *my_object, const char *my_format, ...)
  __attribute__ ((format (printf, 2, 3)));
(Now I like rust's solution better, a sane macro system so this interface doesn't have to be special cased by the compiler to be safe).
Re:Accidentally Overwriting Another Local Variable in C and C++ by jdashg on Thursday December 05, 2019 @07:13PM (#21718132)
This is best-practice. Varargs will bite you if you don't have the compiler check your work, but fortunately they're happy to do so these days.
Re:Accidentally Overwriting Another Local Variable in C and C++ by DerekL on Thursday December 05, 2019 @08:15PM (#21718472)
C++20 is adding a type-safe alternative to printf, called std::format, though it doesn't provide warnings at compile time.
Re:Accidentally Overwriting Another Local Variable in C and C++ by excessive on Thursday December 05, 2019 @10:03PM (#21718926)
Here's one you can use with (pretty much) any version of C++:

    __attribute__ ((format (printf, 1, 2))) 
    static inline std::string format(const char* fmt, ...) {
        va_list args;
        va_start(args, fmt);
        size_t bytes = vsnprintf(0, 0, fmt, args);
        va_end(args);
    
        va_list again;
        va_start(again, fmt);
        std::string result(bytes, '\0');
        vsnprintf(&result[0], bytes + 1, fmt, again);
        va_end(again);
        return result;
    }
Re:Accidentally Overwriting Another Local Variable in C and C++ by Ididntdothis on Thursday December 05, 2019 @09:40PM (#21718820)
They should have gone step further and done string interpolation how C# and JS can do. Really nice to use and avoids errors.