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?
You could try preprocessor directives, but that might not be what they are looking for.
Just look to see if the __STDC__
and __cplusplus
compiler macros are defined.
Simple enough.
#include <stdio.h>
int main(int argc, char ** argv) {
#ifdef __cplusplus
printf("C++\n");
#else
printf("C\n");
#endif
return 0;
}
Or is there a requirement to do this without the official standard?
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.
#include <stdio.h>
typedef int X;
int main()
{
struct X { int ch[2]; };
if (sizeof(X) != sizeof(struct X))
printf("C\n");
else
printf("C++\n");
}
I'm guessing the intent is to write something that depends on differences between the languages themselves, not just predefined macros. Though it's technically not absolutely guaranteed to work, something like this is probably closer to what's desired:
int main() {
char *names[] = { "C", "C++"};
printf("%s\n", names[sizeof(char)==sizeof('C')]);
return 0;
}
I know of 6 approaches:
sizeof
.//
comments. (This won't work with C99.)sizeof
differences with char
literals. Note that this isn't guaranteed to be portable since it's possible for some hypothetical platform could use bytes with more than 8 bits, in which case sizeof(char)
could be the same as sizeof(int)
.(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
Edit: Added method 6, and added a note that method 5 isn't strictly legal.