Monday, September 16, 2013

Strings without escape characters

Does this look familiar?
        \"Action\":\"Upload\",
        \"FromVersion\":\"ver1\",
        \"ToVersion\":\"ver2\"

Wouldn't it be awesome to be able to write like this instead?
        "Action":"Upload",
        "FromVersion":"ver1",
        "ToVersion":"ver2"

Escape characters exists for a simple reason. It says "do not interpret the character after as it should be interpreted". But if we are writing Json we should put escape character way too often. The resulting string could be unreadable. But a simple solution exists:

  1. #define MAKE_STRING(...)  #__VA_ARGS__

...

  1. const char *json(MAKE_STRING( {
  2.         "Action":"Upload",
  3.         "FromVersion":"ver1",
  4.         "ToVersion":"ver2" } );

Done! That simple. Here we use a technique called stringification. It accepts a variadic macro, variable number of arguments, in other words. And it stringifies them! Meaning it produces strings. So all the parameters are stringified and then concatenated separately, because two string in C are always concatenated if put next to each other, i.e.

  1. "foo" "bar"

will produce "foobar". Note, that I'm talking about strings here, not the pointers to array of chars or string objects from C++. No, pure strings, such as "I'm a string".

This technique should work on all modern compilers. Was tested on GCC, Clang, MS compiler.

No comments:

Post a Comment