Monday, 14 January 2013

Minor Differences Between C and C++

  There are some major differences between C and C++. You can refer a good C++ programming text book to find those differences. Here in this post I am discussing about a few subtle differences between C and C++. I have tried to include as many points as possible, but still there might be some points missing.
  • In C by default the return type of a function is integer. But this rule is not valid in C++. You have to mention the return type as integer explicitly. 
                               add( )  // Valid in C.
                               add( )  // Error in C++.
  • In C an empty function prototype tells the compiler that the function can have any number of arguments. But in C++ it means the function does not take any argument.
                               int add( );  // in C this function can take any number of arguments.
                               int add( );  // in C++ this function does not take any arguments.  
  • Structure variable declaration is different for C and C++. Consider the structure given below. 
                              struct sample
                              {
                                  int x,y;
                              };
          In C structure variable is declared as follows.
                             struct sample var1;
          In C++ structure variable is declared as follows.                               
                             sample var1;
  • Built-in memory-handling operators new and delete are available in C++. In C dynamic memory allocation is done with the help of functions malloc( ) and free( ).
  • Single line comment ( // ) is available in C++.
  • Address of register variable can be taken in C++. But in C it is not possible.
  • Size of enumeration constant is that of integere in C. But in C++ size of enumeration variable is not fixed. It depends on the size requirement of the enumeration constant.
  • Anonymous unions can be declared in C++.
  • Anonymous enumeration is possible in C++ if just enumeration constants are required.
  • C++ preprocesser provides an additional predefined macro constant __cplusplus.
  • The unary increment and decrement operators in C++ returns an lvalue. But in C they return an rvalue.
                            (++i)++;  // Error in C, but in C++ it is valid.
                            ++i=0;    // Error in C, but in C++ it is valid.      
       

No comments:

Post a Comment