[ create a new paste ] login | about

Link: http://codepad.org/qYUfXcmR    [ raw code | output | fork ]

C, pasted on Jul 2:
  #include <stddef.h>
  #include <stdio.h>

  typedef unsigned char byte__;

  /* Derived from Chris M. Thommason */
  #define STRING_ALIGNMENT(str) (    \
      offsetof(                      \
          struct {                   \
              byte__ b;              \
              char ca[sizeof (str)]; \
            },                       \
          ca                         \
        )                            \
    )

  #define STRING_STRUCT(str)               \
    struct {                               \
        byte__ pre[STRING_ALIGNMENT(str)]; \
        char ca[sizeof (str)];             \
      }

  #define STRING_STRUCT_INIT(str) {     \
      .pre = {                          \
          [STRING_ALIGNMENT(str) - 1] = \
            sizeof (str),               \
        },                              \
      .ca = str,                        \
    }

  #define STRING_UNION(str)                     \
    union {                                     \
        STRING_STRUCT(str) s;                   \
        byte__ ba[sizeof (STRING_STRUCT(str))]; \
      }

  #define STRING(str) (                \
      (char *) (                       \
          (STRING_UNION(str)) {        \
              STRING_STRUCT_INIT(str), \
            }.ba +                     \
          STRING_ALIGNMENT(str) -      \
          1                            \
        )                              \
    )

  static char * foo = STRING("foo");
  static char * bar = STRING("hum a few bars");
  static char * baz = STRING("very, very baz");

  static void dump_string(char * string) {
      printf("size: %d, chars: { ", *string);
      while (*++string)
        printf("'%c', ", *string);
      printf("'\\0' }\n");
      return;
    }

  int main(void) {
      dump_string(foo);
      dump_string(bar);
      dump_string(baz);
      return 0;
    }


Output:
1
2
3
size: 4, chars: { 'f', 'o', 'o', '\0' }
size: 15, chars: { 'h', 'u', 'm', ' ', 'a', ' ', 'f', 'e', 'w', ' ', 'b', 'a', 'r', 's', '\0' }
size: 15, chars: { 'v', 'e', 'r', 'y', ',', ' ', 'v', 'e', 'r', 'y', ' ', 'b', 'a', 'z', '\0' }


Create a new paste based on this one


Comments: