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
Is C++0x Compatible with C?
C++0x (later standardized as C++11) is not fully compatible with C, just as previous C++ standards were not. While C++ was designed to be largely compatible with C, there are several key differences that prevent full compatibility.
Syntax
// C code that may not compile in C++ // or behaves differently
Key Compatibility Issues
Example 1: Implicit void* Conversion
In C, you can implicitly convert from void* to other pointer types. C++ requires explicit casting −
#include <stdio.h>
#include <stdlib.h>
int main() {
/* This works in C but not in C++ */
int *ptr = malloc(sizeof(int) * 5);
if (ptr != NULL) {
*ptr = 42;
printf("Value: %d\n", *ptr);
free(ptr);
}
return 0;
}
Value: 42
Example 2: Different Keywords
C++ has additional keywords that are valid identifiers in C −
#include <stdio.h>
int main() {
/* These are valid variable names in C but keywords in C++ */
int class = 10;
int new = 20;
int delete = 30;
printf("class = %d, new = %d, delete = %d\n", class, new, delete);
return 0;
}
class = 10, new = 20, delete = 30
Example 3: Character Literal Size
The size of character literals differs between C and C++ −
#include <stdio.h>
int main() {
/* In C, 'A' is of type int (usually 4 bytes) */
/* In C++, 'A' is of type char (1 byte) */
printf("Size of 'A' in C: %zu bytes\n", sizeof('A'));
printf("Size of char: %zu bytes\n", sizeof(char));
return 0;
}
Size of 'A' in C: 4 bytes Size of char: 1 bytes
Major Differences Summary
| Feature | C | C++ |
|---|---|---|
| void* conversion | Implicit | Explicit cast required |
| Character literals | int type | char type |
| Function declarations | int func(); means any parameters | int func(); means no parameters |
| Reserved keywords | 32 keywords | 95+ keywords |
Conclusion
C++0x/C++11 maintains the same compatibility limitations with C as previous C++ standards. While most C code can be compiled as C++, full compatibility was never a design goal, and certain C constructs will always require modification to work in C++.
