Alex Rivera | Logout

Write a program that will print "C" if compiled as an (ANSI) C program, and "C++" if compiled as a C++ program

Asked 2010-01-10T19:14:33.347
18

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?

Edit
Report

3 Answers

31

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?

answered 2010-01-10T19:17:06.233
1

One word, __cplusplus.

answered 2010-01-10T19:16:20.423
0

For what it's worth, here's another answer:

char x[sizeof(char *)+2], y[1];
printf("%.*s\n", sizeof(1?x:y)-sizeof(char *)+1, "C++");
answered 2011-06-25T15:35:28.513

Your Answer