Jaa


Howto distinguish between a C and C++ program

Q: Write a piece of code that compiles as both C and C++, but from the execution you can determine under which mode they were compiled

This is the question which I overheard Amit and Srivatsn discussing before I left office. Obviously you cannot go to sleep if you don't get that nailed. So after pondering for some time I came up with the following code.

 #include <stdio.h>int main(int argc, char* argv[]){     // 1: Using comments    int val = 42//* WooHoo*/ 2;    ;    val == 42 ? printf("C++\n"): printf("C\n");
    // 2: Using sizeof
    sizeof('a') == sizeof(char) ? printf("C++\n"): printf("C\n");    return 0;}

If this code is placed in a .cpp filed and compiled in VS the output is C++, C++ and if placed in a .c file with language extensions disabled the output is C, C. If you are using the Microsoft Compiler this is how you do it

 c:\> cl CCPP.c  /Za
c:\> CCPP.exe
 c:\> cl CCPP.cpp
c:\> CCPP.exe

The second approach is trivial because in CPP the sizeof a literal character matches 
sizeof a char and in case of C it matches sizeof an int.

However the first approach is kind of tricky. Lets conside the code

 int val = 42//* WooHoo*/ 2;;

In C++ all the characters after // is considered as comment and hence this is compiled as

 int val = 42;

However C doesn't recognizes the // comment and this gets compiled as

 int val = 42/ 2;;

I'm sure people can think up of other approaches....

Comments

  • Anonymous
    July 27, 2006
    C99 supports // comments.
  • Anonymous
    July 27, 2006
    oh I now remember that it does :(
  • Anonymous
    July 27, 2006
    Nice solution! Of course, the ulterior motive here was to spoil your sleep last night :)
  • Anonymous
    August 03, 2006
    Why not just:

    #ifdef __cplusplus
    #define COMPILER "CPP"
    #else
    #define COMPILER "C"
    #endif
  • Anonymous
    August 03, 2006
    The comment has been removed