Monday, February 16, 2009

The Major Differences of C and C++

When I taught C++ using Bloodshed C, I indeed had my struggle, but as I learned the ins and outs of C++, somehow I find the transition between the two languages. They are quite similar with structures and all except for other stuffs listed below:

For input and output commands in C:
scanf() and printf()

For C++:
cin>> and cout<< */
using namespace std;

These control the input and output functions and variables that are used in the program.
To ignore the return key after set of inputs, we have to issue a command:


If in C, we use the command getche() or getchar() to wait for keyboard hit to see the result, in C++, we use the command, cin.get() instead.

To display a newline, in C, we use \n while in Bloodshed C++, we use endl.

Check our these two sample programs in C and C++.

[+/-] show/hide

In C:
#include stdio.h /*enclose the stdio.h in between <> */
int a,b,sum;
printf("\nInput your first number : ");
printf("\nInput your second number : ");
printf("\nThe sum of %d and %d is %d",a,b,sum);

In Bloodshed C++

#include iostream /*enclose the iostream in between <> */
using namespace std;

int a,b,sum;
cout<<"Input your first number : "; cin>>a;
cout<<"Input your second number : "; cin>>b;

/* the \ symbol means to concatenate the succeeding lines*/
cout<<<"The sum of "<< \ a<< \ "and "<< \ b << \ " is "<< \ sum;

Are the outputs the same?
There are still differences between C and C++. Do check other related articles.

No comments: