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
-
Economics & Finance
Selected Reading
Write a program that produces different results in C and C++
Here we will see some programs that produce different results when compiled with C and C++ compilers. These differences arise from how C and C++ handle certain language features differently.
Difference 1: Character Literal Size
In C, character literals are treated as int type, while in C++, they are treated as char type. This affects the result of the sizeof() operator −
Example: C Compiler
#include <stdio.h>
int main() {
printf("The character: %c, size(%d)\n", 'a', sizeof('a'));
return 0;
}
The character: a, size(4)
Example: C++ Compiler
#include <stdio.h>
int main() {
printf("The character: %c, size(%d)\n", 'a', sizeof('a'));
return 0;
}
The character: a, size(1)
Difference 2: Struct Usage
In C, the struct keyword is required when declaring variables of struct type. In C++, the struct name can be used directly without the struct keyword −
Example: C Compiler (Requires struct keyword)
#include <stdio.h>
struct MyStruct {
int x;
char y;
};
int main() {
struct MyStruct st; /* struct keyword required in C */
st.x = 10;
st.y = 'd';
printf("Struct (%d|%c)\n", st.x, st.y);
return 0;
}
Struct (10|d)
Example: C++ Compiler (struct keyword optional)
#include <stdio.h>
struct MyStruct {
int x;
char y;
};
int main() {
MyStruct st; // struct keyword not required in C++
st.x = 10;
st.y = 'd';
printf("Struct (%d|%c)\n", st.x, st.y);
return 0;
}
Struct (10|d)
Difference 3: Boolean Expression Size
Boolean expressions in C evaluate to int type (4 bytes), while in C++ they evaluate to bool type (1 byte) −
Example: C Compiler
#include <stdio.h>
int main() {
printf("Bool size: %d\n", sizeof(1 == 1));
return 0;
}
Bool size: 4
Example: C++ Compiler
#include <stdio.h>
int main() {
printf("Bool size: %d\n", sizeof(1 == 1));
return 0;
}
Bool size: 1
Advertisements
