Tomer Gabel's annoying spot on the 'net RSS 2.0
# Tuesday, 26 September 2006

This wasn't an easy riddle by any means. One has to either have a lot of experience developing both C and C++, or take a very hard look at the standards to spot the differences. Bottom line? I couldn't find a solution. Fortunately a brother and a colleague both came through:

Solution 1: Ugly Hack

Tal (one of my colleagues at Monfort) came up with the following concept:

#include <stdio.h>

int main()
	int a = 1//**/10
	printf( "%d\n", a );
	return 0;

This deserves some explanation: originally C did not support single-line comments (//); these were added to a later version of the standard called C99. So what happens is, if you compile this code with an old C compiler the "//**/" string is parsed as a division operator and an empty comment, resulting in 1/10=0. A modern C compiler (or any C++ compiler) will treat the entire line as a comment and the result is 1.  One way to easily test this is to compile with gcc -std=c89 file.c.

Solution 2: Elegant Hack

I didn't have the time to properly look for a detailed comparison of C and C++ standards (I'll save you the time: this looks to be a good source). There are probably quite a few ways to achieve the goal, however my brother Mickey suggested one I find quite elegant:

#include <stdio.h>

int main()
	printf( "%d\n", sizeof( 'c' ) == sizeof( char ) );
	return 0;

Seems odd? Apparently one of the (relatively small) breaking changes between C and C++ is how character literals are handled. In C a character literal takes the type int, whereas in C++ a character literal has the expected size (source).

Tuesday, 26 September 2006 10:43:14 (Jerusalem Standard Time, UTC+02:00)  #    -
Send mail to the author(s) Be afraid.
<2017 March>
All Content © 2017, Tomer Gabel
Based on the Business theme for dasBlog created by Christoph De Baene (delarou)