C / C++ FAQs & Programming Resources - ProkutFAQ : CcodeNotCPP

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

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<stdio.h>
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<stdlib.h>
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<stdio.h>
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.

For more such differences, read the article by David R. Tribble on Incompatibilities between ISO C and ISO C++.
 Comments [Hide comments/form]
This will not compile under c++ but will compile in C
-- proxy.iiit.ac.in (2006-10-14 12:18:23)
for the second program when we pass the arguments how will it accept and calculate in c....
-- 221-134-208-203.sify.net (2007-07-31 13:15:27)
ya........ur question is right.Even I am having the same doubt.
-- 123.236.92.91 (2008-12-26 13:59:01)
Can we somehow get an access the stack addresses for these passed values since they reside on the stack on function being called?
-- cpe-76-185-58-5.tx.res.rr.com (2009-06-16 19:21:41)
That depends on your implementation. If you do find out a way to access them, your method would not apply for other compiler implementations because the C standard does not specify how the underlying storage is taken care of - stack/heap or whatever.
-- SharathAV (2009-06-18 15:13:11)
Page was generated in 0.0423 seconds