Hacker News new | past | comments | ask | show | jobs | submit login

A macro for calculating the size of a buffer for a C-style string containing a (signed/unsigned) integer:

  #define CS_INT_SIZE(int_type) ((size_t)(0.30103 * sizeof(int_type) * 8) + 2 + 1)

  int x = -1000;
  char buf[CS_INT_SIZE(x)]; // instead of char buf[100];
  snprintf(buf, sizeof(buf), "%d", x);
Another macro for calculating the length of a string literal in compile time (just like strlen would do). Note the extra check for string literal.

  #define CSLLEN(s)           (sizeof(s "") - 1)
  int len = CSLLEN("hello"); // len == 5 here
Another one for logging variable arguments or no arguments at all.

  #define Log_Trace_(...) Log(__FILE__, __LINE__, __func__, LOG_TYPE_TRACE, "" __VA_ARGS__)
  void Log(const char* file, int line, const char* func, int type, const char* fmt, ...);
  Log_Trace(); // prints just the name of the file, line and func
  Log_Trace("Error %d", error); // prints the same as above and the error number



Why not just declare "char buf[100]" for snprintf's target and be done with it?


Because then you'd have a buffer overflow in 2153 when we're using 512-bit integers.


No, you'd have a truncated string.

You really think we'll be dealing with 512 bit integers in 40 years? This is code that's turning integers into decimal strings.


Either my calendar is wrong, or 2153 is far more than 40 years away.

I wasn't being serious, though.


Sorry. I can't read today. :)


Your logging example is invalid. A variadic macro must be invoked with at least one argument matching the ellipsis. GCC is forgiving here, but some other compilers are not.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: