3 ms·
This isn’t exactly surprising. With functions like printf and scanf you always have to be super careful to pass the right data types. It may work with one OS or
by Ididntdothis 7y ago
This isn’t exactly surprising. With functions like printf and scanf you always have to be super careful to pass the right data types. It may work with one OS or compiler but not with the other. You are actually lucky if your stuff crashes. Otherwise it will just keep going now with wrong values.
- monocasa 7y agoAt 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).
- jdashg 7y agoThis 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.
- DerekL 7y agoC++20 is adding a type-safe alternative to printf, called std::format, though it doesn't provide warnings at compile time.
- Ididntdothis 7y agoThey should have gone step further and done string interpolation how C# and JS can do. Really nice to use and avoids errors.
- excessive 7y agoHere'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; }