Code valid in both C and C++ but produce different output

CC++Server Side ProgrammingProgramming

Here we will see some program that will return different results if they are compiled in C or C++ compilers. We can find many such programs, but here we are discussing about some of them.

  • In C and C++, the character literals are treated as different manner. In C, they are treated as int but in C++, they are treated as characters. So if we check the size using sizeof() operator, it will return 4 in C, and 1 in C++.

Example

 Live Demo

#include<stdio.h>
int main() {
   printf("The character: %c, size(%d)", 'a', sizeof('a'));
}

Output

The character: a, size(4)

Example

#include<iostream.h>
int main() {
   printf("The character: %c, size(%d)", 'a', sizeof('a'));
}

Output (C++)

The character: a, size(1)

In C if we use struct, then we have to use struct tag when we are using it until some typedef is used. But in C++, we do not need to struct tag to use structures.

Example

 Live Demo

#include<stdio.h>
struct MyStruct{
   int x;
   char y;
};
int main() {
   struct MyStruct st; //struct tag is present
   st.x = 10;
   st.y = 'd';
   printf("Struct (%d|%c)", st.x, st.y);
}

Output (C)

Struct (10|d)

Example

 Live Demo

#include<iostream>
struct MyStruct{
   int x;
   char y;
};
int main() {
   MyStruct st; //struct tag is not present
   st.x = 10;
   st.y = 'd';
   printf("Struct (%d|%c)", st.x, st.y);
}

Output (C++)

Struct (10|d)

The size of the Boolean type data are different in C and C++.

Example

 Live Demo

#include<stdio.h>
   int main() {
   printf("Bool size: %d", sizeof(1 == 1));
}

Output (C)

Bool size: 4

Example

 Live Demo

#include<iostream>
   int main() {
   printf("Bool size: %d", sizeof(1 == 1));
}

Output (C++)

Bool size: 1
raja
Published on 17-Dec-2019 17:54:17
Advertisements