Can you write a code which compiles in C but not in C++ ?
This question puzzles many who believe that C++ is a superset of C language, and all C language code is valid in C++. But it is not true and you should read the differences between C and C++
to know how they are different.
Below are few examples which compiles in C and would fail to compile in C++:
This will not compile under C++ because class
is a keyword, but will compile in C without any problems. Similarly any keywords which are specific to C++ such as public
etc can be used as identifiers in C, but not in C++.
This will fail to compile in C++, because in C++, the declaration of a function with no argument list is equivalent to declaring it as function with void parameter list. But in C language, it means a function with unspecified number of arguments and we can pass any number of arguments to this function in C.
This is valid in C because a pointer of type void* can be assigned to any other pointer without cast, but this is not in valid C++ because will have to give an explicit cast to it as in:
This code is valid in C because recursion of main function is legal in C language whereas it is illegal in C++ language.
For more such differences, read the article by David R. Tribble on Incompatibilities between ISO C and ISO C++∞