Write a program that produces different results in C and C++
In this tutorial, we'll explore several programs that, depending on whether they are developed using C or C++ compilers, will produce varying outputs. There are numerous similar programs, but we will just clarify a few here.
1. The way in which character literals are handled in C and C++ differs. 'x' , 'y'.., and other character literals are interpreted as characters in C++ but as integers in C. Details are provided here.
As an illustration, the following program outputs sizeof(int) in C but sizeof(char) in C++.
C Program:
#include<stdio.h>
int main ()
{
printf ( "%d", sizeof ('x') );
return 0;
}
Output:
4
C++ Program:
#include<iostream>
using namespace std;
int main ()
{
cout << sizeof ('x');
return 0;
}
Output:
1
2. The struct label must be used each and every time when a struct variable is declared in C. Struct tags are not required in C++. Let's say that there is a structure for kids. For kids variables in C, we need to use 'struct kids'. We can only use "kids" in C++ instead of the struct.
The program that follows, which generates various outputs in both C and C++, is based on the fact. Sizeof (int) and sizeof (struct k) are printed in C and C++, respectively.
C Program:
#include <stdio.h>
int k;
int main ()
{
struct k {
double y
}; // This k covers up the global variable k in C++, but not in C.
printf ( "%d", sizeof (k) );
return 0;
}
Output:
4
C++ Program:
#include <iostream>
using namespace std;
int k;
int main ()
{
struct k {
double y;
}; // This k covers up the global variable k in C++, but not in C.
cout << sizeof (k) ;
return 0;
}
Output:
8
3. In C and C++, different boolean result types are found.
C Program:
#include <stdio.h>
int main ()
{
printf ("%d",sizeof (2==2) );
return 0;
}
Output:
4
C++ Program:
#include <iostream>
using namespace std;
int main ()
{
cout << sizeof ( 2==2 );
return 0;
}
Output:
1