JoshuaWise.com

A small list of C brainteasers


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
c-brainteasers [2012/11/30 07:58]
joshuawise
c-brainteasers [2013/10/11 00:21]
joshuawise
Line 38: Line 38:
   * //(taken from elsewhere on the Web)// Without running it, what is the output of the following program? \\ ''int main(void) {int n = sizeof(0)["abcdefghij"]; printf("%d\n", n); return 0; }''   * //(taken from elsewhere on the Web)// Without running it, what is the output of the following program? \\ ''int main(void) {int n = sizeof(0)["abcdefghij"]; printf("%d\n", n); return 0; }''
     * It is not machine-specific.     * It is not machine-specific.
 +  * A common idiom in C is ''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?
 +    * More concretely: it is easy to write a static assert macro that fails to compile if a given expression is either a) false, or b) not compile-time constant.  Your task is to write a static assert macro that fails to compile if a given expression is a) true **and** b) a compile-time constant!
 +    * Here are some test cases, if you care: <code>
 +ASSERT_CHECKER(time());
 +ASSERT_CHECKER(0);
 +ASSERT_CHECKER("abc"[2]);
 +ASSERT_CHECKER(!"biteme");
 +ASSERT_CHECKER("biteme");
 +ASSERT_CHECKER(2 + 2);</code> 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.
 +  * //(C++11-only)// Find a use for the token sequence ''......''.
  
 I've enabled comments below, but please don't post spoilers. I've enabled comments below, but please don't post spoilers.
  
 ~~DISQUS~~ ~~DISQUS~~