Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Write a program that produces different results in C and C++
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++.
Live Demo For C.
Example
#include<stdio.h>
int main() {
printf("The character: %c, size(%d)", 'a', sizeof('a'));
}
Output(C)
The character: a, size(4)
Live Demo For C.
Example
#include<stdio.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.
Live Demo For C.
Example
#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)
Live Demo For C++.
Example
#include<stdio.h>
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++.
Live Demo For C.
Example
#include<stdio.h>
int main() {
printf("Bool size: %d", sizeof(1 == 1));
}
Output(C)
Bool size: 4
Live Demo For C++.
Example
#include<stdio.h>
int main() {
printf("Bool size: %d", sizeof(1 == 1));
}
Output(C++)
Bool size: 1
