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”.
See Also
- 2.4 > 2.6 in OpenWrt - November 29, 2009
- Slicehost kernel upgrade - November 1, 2009
- Eee Kernel 2.6.31.2-1 Update - October 6, 2009
- Eee Kernel Scheduler Tweaks - September 25, 2009
- Arch Kernel Eee 2.6.31 built - September 9, 2009