Taken from http://www.ocf.berkeley.edu/~wwu/riddles/cs.shtml
It looks very compiler specific to me. Don't know where to look for?
Taken from http://www.ocf.berkeley.edu/~wwu/riddles/cs.shtml
It looks very compiler specific to me. Don't know where to look for?
I know of 7 approaches:
1. Abuse C++ automatic
typedef
s(Note that the struct needs to be declared in an inner scope so that it takes precedence over the outer name in C++.)
A similar version that doesn't rely on the ambiguity between
sizeof (type)
andsizeof (variable)
, using only types:2. Abuse C++
struct
/class
equivalence, automatictypedef
s, and automatically-generated default constructors3. Abuse nested
struct
declarations in CAlso see Symbol clashing of inner and outer structs, C++ vs C
4. Abuse
//
commentsThis won't work with C99 or with C89 compilers that support
//
as an extension.or alternatively:
5.
sizeof
differences withchar
literalsNote that this isn't guaranteed to be portable since it's possible that some hypothetical platform could use bytes with more than 8 bits, in which case
sizeof(char)
could be the same assizeof(int)
. (Also see Can sizeof(int) ever be 1 on a hosted implementation?)6. Abuse differences in when lvalue⇒rvalue conversions are performed
This is based off of the 5.16, 5.17, 5.18 example in the ISO C++03 standard, and it works in gcc but not in MSVC (possibly due to a compiler bug?).
7. Abuse differences in the way C and C++'s grammars parse the ternary operator
This one isn't strictly legal, but some compilers are lax.
(You also could check for the
__cplusplus
preprocessor macro (or various other macros), but I think that doesn't follow the spirit of the question.)I have implementations for all of these at: http://www.taenarum.com/csua/fun-with-c/c-or-cpp.c
One word,
__cplusplus
.We had to do a similar assignment at school. We were not allowed to use preprocessor (except for
#include
of course). The following code uses the fact that in C, type names and structure names form separate namespaces whereas in C++ they don't.