what is the difference between c and c++? explain it with example.

what is difference between c and cpp

Let us try to compile below sample code with gcc and g++. 

#include<stdio.h>

int main ()
{
  char c;
  printf("%ld\n",sizeof(c));
  printf("%ld\n",sizeof('a'));
  return 0;
}

When we run the program after compilation from gcc ( cits output would be

1
4

When we run the program after compilation from g++ its output would be

1
1

In C, the type of a character constant like ‘a’ is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1.

 what is difference between c and cpp enum

In C language, an enum assign integers to names while in C++, an enum defines an actual type, which results in strong type checking. so following example will compile in c++ and would not compile in c.

#include<stdio.h>

int main ()
{
  enum surname
  {
    bk,
    ck,
    dk
  };

  surname alt = dk; // error in c but works in c++

  printf("%d\n",alt);
  return 0;
}

When we compile above program in c (gcc compiler) it would give error during compilation. we will get below error.

t.c: In function ‘main’:
t.c:12:3: error: unknown type name ‘surname’
   surname alt = dk; // error in c but works in c++
   ^

If we replace line 12 with “enum surname alt = dk” then the above program would compile in c successfully.

c++ provides strong type checking compare to c language.

Let us compile the below code in c and c++

#include<stdio.h>
#include<stdlib.h>

int main ()
{
  char *str;
  str = malloc(10*sizeof(char));
  return 0;
}

The above code will compile in c while it will not compile in c++. ‘g++ t.c’ command results in error like following

t.c: In function ‘int main()’:
t.c:7:31: error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
   str = malloc(10*sizeof(char));

In c , the void * is promoted to char * ( in above program), while in c++ we require to typecast explicitly.  so the above program needs modification to  be compiled in c++. Below is modified code , that will compile in c and c++ without any error.

#include<stdio.h>
#include<stdlib.h>

int main ()
{
  char *str;
  str = (char*)malloc(10*sizeof(char));
  return 0;
}

Ref:

http://www-cs-students.stanford.edu/~sjac/c-to-cpp-info/c-to-cpp-differ



Related Contents to follow