Hacker News new | ask | show | jobs
by kazinator 2161 days ago
You could do this in GNU C probably at least as far back as 1990. In GNU C, this syntax:

  ({ expr1; expr2; ... ; exprN })
gives you something like a Lisp progn: it's an expression, whose value is exprN.

Complete sample:

  #include <stdio.h>
  
  int main(int argc, char **argv)
  {
    char *foo = (argc > 1) ? ({
                  printf("consequent\n");
                  "condition is true: I have arguments";
                }) : ({
                  printf("alternative\n");
                  "condition is false: I don't have arguments";
                });
    puts(foo);
  }
This is almost certainly because RMS is a Lisp hacker. I.e. why GCC uses Lisp notations internally and functions with "mapcar" in the name and such.

I discovered it by accident sometime in 1993. I wanted the value of the last expression in a braced block. Maybe it can forced into an expression if you just put parentheses on it? By golly, the intuition worked.

Mainly, it is used in writing macros. Speaking of which:

  #include <stdio.h>

  #define ifblock(expr) (expr) ? (
  #define elseblock ) : (
  #define endblock )

  int main(int argc, char **argv)
  {
    char *foo = ifblock (argc > 1) {
                  printf("consequent\n");
                  "condition is true: I have arguments";
                } elseblock {
                  printf("alternative\n");
                  "condition is false: I don't have arguments";
                } endblock;
    puts(foo);
  }