toofishes.net

GCC compound statement expressions

GCC has a rather crazy syntax that I discovered tonight for the first time, and I thought I’d share so you don’t have to dig for a half hour like I did to find out what it is and how it works. The feature is compound statment expressions. I came across it in the Linux kernel code in include/linux/percpu.h:

#define per_cpu_ptr(ptr, cpu) ({ (void)(cpu); (ptr); })

The long and short of this expression is this- if you call per_cpu_ptr(myptr, 5), you will get myptr back. But the macro to do this confused me, with no explicit return.

With a compound statement expression, as opposed to just a compound statement (those things surrounded by curly braces), the last item in the block is used as the return value for the whole expression. Thus, in the above expression, the value of ptr will be returned. The key is including both the parenthesis and curly braces.

If you want to see a full example, check out the following (working) program.

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    int number;
    char *string;

    string = ({ "hidden"; "shown"; });
    number = ({ int a = 50; a += 50; a; });

    printf("%s %d\n", string, number);
    return 0;
}

If compiled with gcc test.c, it should produce the output “shown 100”.

Tags

See Also