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
Code valid in both C and C++ but produce different output
Here we will see programs that return different results when compiled with C or C++ compilers. These differences arise due to fundamental variations in how C and C++ handle certain language features.
Character Literal Size Differences
In C, character literals like 'a' are treated as int type, while in C++ they are treated as char type. This affects the result of the sizeof() operator −
Example 1: C Code
#include <stdio.h>
int main() {
printf("Character: %c, Size: %d bytes\n", 'a', sizeof('a'));
return 0;
}
Character: a, Size: 4 bytes
Example 2: Equivalent C++ Code
The same code compiled as C++ would produce different output −
#include <iostream>
#include <cstdio>
int main() {
printf("Character: %c, Size: %d bytes\n", 'a', sizeof('a'));
return 0;
}
Character: a, Size: 1 bytes
Structure Declaration Differences
In C, you must use the struct keyword when declaring structure variables, but C++ allows omitting it −
Example 3: C Structure Usage
#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 values: x = %d, y = %c\n", st.x, st.y);
return 0;
}
Struct values: x = 10, y = d
Example 4: C++ Structure Usage
In C++, the struct keyword is optional −
#include <iostream>
#include <cstdio>
struct MyStruct {
int x;
char y;
};
int main() {
MyStruct st; // 'struct' keyword not required in C++
st.x = 10;
st.y = 'd';
printf("Struct values: x = %d, y = %c\n", st.x, st.y);
return 0;
}
Boolean Expression Size
Boolean expressions have different sizes in C and C++. In C, boolean expressions return int (typically 4 bytes), while C++ has a dedicated bool type (1 byte) −
Example 5: Boolean Size in C
#include <stdio.h>
int main() {
printf("Boolean expression size: %d bytes\n", sizeof(1 == 1));
return 0;
}
Boolean expression size: 4 bytes
Key Differences Summary
| Feature | C Behavior | C++ Behavior |
|---|---|---|
Character literal 'a'
|
int type (4 bytes) | char type (1 byte) |
| Structure declaration | struct keyword required | struct keyword optional |
| Boolean expressions | int type (4 bytes) | bool type (1 byte) |
Conclusion
These differences highlight the importance of understanding language-specific behaviors when writing code that needs to be compatible with both C and C++ compilers. Character literals, structure declarations, and boolean types are key areas where the languages diverge.
