0

Need to write a C program. If it is run in the C language compiler, the program should print "C". If it is run in the compiler C++, it should print "C++".

Preprocessor directives can not be used.

In head comes only to compare the size of any character with the char size like:

sizeof(char)==sizeof('a')

Here how it works:

// C code:
#include <stdio.h>
int main()
{
    printf("%s", (sizeof(char)==sizeof('a') ? "C++" : "C"));
    return 0;
}

Output: C

// C++ code:
#include <stdio.h>
int main()
{
    printf("%s", (sizeof(char)==sizeof('a') ? "C++" : "C"));
    return 0;
}

Output: C++

There, a better way?

Amazing User
  • 3,473
  • 10
  • 36
  • 75

2 Answers2

2

You can check the __cplusplus macro to see if you're being compiled as c++.

#include <stdio.h>

int main()
{
    printf("%s\n",
#if __cplusplus
            "C++"
#else
            "C"
#endif
          );
}
Kevin
  • 53,822
  • 15
  • 101
  • 132
  • 1
    `Preprocessor directives can not be used.`. But you might as well do the humorous `#if true` trick. –  Feb 20 '14 at 19:56
2

The standard http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf Contains an appendix on the differences between C and C++

So it contains the char vs int difference which you use but also for instance

Change: In C++, a class declaration introduces the class name into the scope where it isdeclared and hides any object, function or other declaration of that name in an enclosing scope. In C, an inner scope declaration of a struct tag name never hides the name of an object or function in an outer scope

Example: (from the standard)

int x [99];
void f () {
     struct x { int a ; };
     sizeof (x ); /∗ size of the array in C ∗/
                  /∗ size of the struct in C++ ∗/
}

To which gcc gave 396 and g++ 4 on my machine

odedsh
  • 2,594
  • 17
  • 17