Thursday, August 28, 2008

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++:
Example 1:
#include
int main()
{
int class;
class=10;
printf("%d",class);
}

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, private, virtual, friend etc can be used as identifiers in C, but not in C++.

Example 2:
int fun()
{
//some code
}
int main()
{
fun(10,20);
}

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.

Example 3:
#include
int main()
{
int *array=malloc(sizeof(int)*100);
}

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:
int *array=(int*)malloc(sizeof(int)*100);


Example 4:
#include
int main()
{
static int i=5;
if(i>0)
printf("%d\n",i);
else
{
i--;
main();
return 0;
}
}


This code is valid in C because recursion of main function is legal in C language whereas it is illegal in C++ language.

0 comments: