Here's a small list of C brainteasers that a few friends and I came up with and/or found. (All problems, except where specified, in C99.)
sizeof ( ... printf(“hey!\n”) ... )
which results in hey!
being printed?...
.sizeof
comes in two forms in C – sizeof ( TYPENAME )
, and sizeof EXPRESSION
. Can you do it with both forms?[ * ]
in a row?restrict 5
?a.c
that results in: jwise@jwise-lt-linux:~$ grep '#' a.c jwise@jwise-lt-linux:~$ grep '{' a.c jwise@jwise-lt-linux:~$ cc -std=c99 -pedantic -Wall -o a a.c && ./a hey!
a2.c
that results in: jwise@jwise-lt-linux:~$ grep '#' a2.c jwise@jwise-lt-linux:~$ grep '{' a2.c jwise@jwise-lt-linux:~$ grep '\[' a2.c jwise@jwise-lt-linux:~$ grep '"' a2.c jwise@jwise-lt-linux:~$ grep "'" a2.c jwise@jwise-lt-linux:~$ gcc -std=c89 -pedantic -o a2 a2.c && ./a2 hey!
a3.c
that results in: jwise@jwise-lt-linux:~$ grep '"' a3.c jwise@jwise-lt-linux:~$ grep "'" a3.c jwise@jwise-lt-linux:~$ grep ';' a3.c jwise@jwise-lt-linux:~$ gcc -std=c99 -pedantic -Wall -o a3 a3.c && ./a3 hey!
a4.c
that results in: jwise@jwise-lt-linux:~$ grep '"' a4.c jwise@jwise-lt-linux:~$ grep "'" a4.c jwise@jwise-lt-linux:~$ grep ';' a4.c jwise@jwise-lt-linux:~$ grep -E '{[^}]|{$' a4.c jwise@jwise-lt-linux:~$ gcc -std=c99 -pedantic -Wall -o a4 a4.c && ./a4 hey!
a
or a2
?gcc
's view of the specification, not clang
's.int main(void) {int n = sizeof(0)[“abcdefghij”]; printf(“%d\n”, n); return 0; }
assert(!“That's not gone well”)
. Unfortunately, a common idiom in C amongst careless programmers is assert(“That's not gone well”)
, or the potentially even more amusing assert(“!That's not gone well”)
. Can you write a macro that chokes with a compile time failure on the latter two cases?ASSERT_CHECKER(time()); ASSERT_CHECKER(0); ASSERT_CHECKER("abc"[2]); ASSERT_CHECKER(!"biteme"); ASSERT_CHECKER("biteme"); ASSERT_CHECKER(2 + 2);
The last two should fail, by the C99 specification. There is an easier way to do it with a GCC extension, but you do not need any GCC extensions to do this.
......
.I've enabled comments below, but please don't post spoilers.
~~DISQUS~~