Friday, November 8, 2013

Same Program, But Different Output on C and C++

The C++ language began as enhancements to C, first adding classes, then virtual functions, operator overloading, multiple inheritance, templates and exception handling, among other features.

We all know that C++ is often considered to be a superset of C, but this is not strictly true. Most C code can easily be made to compile correctly in C++, but there are a few differences that cause some valid C code to be invalid or behave differently in C++.

Here are some examples of the programs, save them with extention '.c' and '.cpp', and compile & run.
These programs are having different outputs on C and C++ :-

First Program :-

 #include <stdio.h>  
 int main(void){  
      printf("%d", sizeof('a'));  
      return 0;  
 }  
Explanation: In C language the character literals as 'a', 'b', '1' etc... are treated as integers, so sizeof returns the size of integer. In C++ language character literals are treated as characters, so sizeof returns the size of character.

Second Program :-

 #include <stdio.h>  
 int main(void){  
      printf("%d", sizeof(1==1));  
      return 0;  
 }  
Explanation: In C language the Boolean result returns either 1 or 0 which is treated as integer, so sizeof returns the size of integers. In C++ Boolean result returns either true or false, so sizeof returns size of Boolean.

Third Program :-

 #include <stdio.h>  
 int T;   
 int main(void){  
      struct T {  
           double x;  
           int y;  
      };  
      printf("%d", sizeof(T));  
      return 0;  
 }  
Explaination: In C language, to declare a structure type variable we need to use struct keyword before it, but in C++ we have not to type the struct. So sizeof(T) returns the size of integer T in C, but size of structure T in C++.

No comments:

Post a Comment