Search code examples
ccompound-literals

Practical uses for compound literal expressions?


What are the practical applications of compound literals? I am not quite sure how an address of an unnamed region of storage could be useful.

int *pointer = (int[]){2, 4};

I found them mentioned here: https://en.cppreference.com/w/c/language/compound_literal


Solution

  • Here are some great ones:

    • Working around interfaces that take a pointer to input rather than a value (possibly to return an updated value you don't have any reason to care about):

      y = accept(x, &sa, &(socklen_t){sizeof sa});
      
    • Implementing functions with named and default-zero/null arguments:

      #define foo(...) foo_func(&(struct foo_args){__VA_LIST__})
      foo(.a=42, .b="hello" /* .c = NULL implicitly */);
      
    • Implementing custom formats for printf (automatically getting per-macro-instantiation temp buffer):

      #define fmt_mytype(x) fmt_mytype_func((char[MAX_NEEDED]){""}, x)
      printf("...%s...", ..., fmt_mytype(foo), ...);