Another way to use the C ternary operator (? :)

Posted in kerneltrap.org on May 12, 2008 – 7:58pm

I found in Linux kernel 2.6.21.5 in include/net/netinet_hastables.h in function __inet_lookup this interesting expression:

return sk ? : __inet_lookup_listener(hashinfo, daddr, hnum, dif);

It turned out that it is actually okay if you omit the operand between ? and : because the operand will be taken from the result of evaluating the first operand (in this case, sk). With other words, the above code will simply return sk if sk is not NULL.

Of course, you cannot omit the operand after : (e.g., sk ? do_something() :). If you do that, the compiler will issue a compile-time error.

This feature is an extension to the C programming language that GCC (GNU Compiler Collection) has. So, if you are not using GCC, this may not work for you.

This entry was posted in C, GCC Extensions, Hacking, Linux Kernel, Programming Languages, Software and tagged . Bookmark the permalink.

Leave a comment