Wednesday, August 26, 2009

Differences between C and C++

Here are some notes from a Programming Language Principles class.

C++ has five major "improvements" over C
  1. Stream I/O
  2. Strong typing
  3. Parameter passing by reference
  4. Default argument values
  5. Inlining
Stream I/O
C++ adds the library which declares two streams cin ( operator>>) and cout (operator<<). The cin stream is associated with standard input and The input lines are buffered and require an end-of-line character before processing input.

Streams are nice because:
  1. Type safe - the type of object in the stream is known at compile time. No dynamic type checking needed with the % operator
  2. Less error prone than printf
  3. Streams are faster than printf.
  4. Streams are extensible to new user-defined data types. So you can read in an object.
  5. Streams are subclassable. ostream and istream are the C++ replacements for the File pointer (FILE*). You can define types that look and act like streams.
Strong Typing
In general, C++ has stronger typing and C.
  1. To express a function with zero arguments in C you must say foo(void) because foo() tells the compiler not to check for input types such as char * malloc();.In C++ the empty argument list means "no arguments."
  2. In C, its ok to call a function that has not been defined. No type checking will be performed. In C++ prior to any function use, you must at least have a prototype defined.
  3. In C++, you are required to return a function of the type you declare. In C, you may choose to return a function of the type you declare or you may choose to simply return;. If you try to use return; when a return type of a function is declared, the compiler say error: return-statement with no value.
  4. In C you are allowed to assign a void* to a pointer of a different type. This will cause an error in C++.
  5. When initializing arrays, the statement char A[2] = "hi" will cause an error in C++ because there is no declared room to add the end of line '\0' character. In C this is ok, and no '\0' is stored ... possibly causing an error with proceeding string functions. It is best to use char A[] = hi;
  6. In C++ we can use new and delete instead of malloc and free. malloc doesn't call constructors and free doesnt call destructors. new and delete are type safe.

I will leave the discussion there. Please feel free to add more.