Sep 25, 2015

Programs that work in C and not in C++


1.
int main()
{
                       int a = fun();
            return 0;
}
int fun()
{
            return 2;
}

As the function prototype is not declared before the function is called, it gives an error in C++. But in C, it works fine.
2.
int main()
{
            const int a;                
            return 0;
}
               
            In C++, the const integer should be initialized at the time of declaration only.
3.
int main()
{
            int c;
            void *b=&c;
            *((int*)b)=10;
            printf("%d",*((int*)b));
return 0;
}

Here the void pointer points to an integer.  For typecasting to int pointer, we need not to use                 explicit type cast as we do in C++. In C, type casting is done through implicit typecast.
4.
int main()
{
            int const a=10;
            int *p=&a;
                       return 0;
}

In C++, only the const pointer can point to the const integers. In C, either const or non-const pointers can point to that object.
5.
int main()
{
            int new =10;
printf("%d",new);
return 0;
}

In C++, new, delete, explicit are Reserved words. As reserved words cannot be used as variables in C++.
6.
int main()
{
            char *p=333;
            printf("%u",p);
            return 0;
}


            In C++, char pointer  can’t point  to an integer variable.


      Also see 

                       1.  4 Pillars of OOP concepts
                       2.  Associativity of Operators 
                       3.  Graph Terminology



Filed under ,  |