Just from memory VLAs and designated initializers are the two C99 features not supported by C++.
But they're available as custom extensions in many C++ compilers (since they mostly happen to be C compilers too) and designated initializers might make it to C++20 last time I checked.
so neither int a = getchar(); int arr[a]; nor int arr[5] = { [1] =50, [4] = 30}; are valid C++, but they are valid C
Aside from new features in C99 that don't exist in C++, implicit type conversions are different, especially for void pointers, which act as an "escape hatch" to the C type system, but require explicit type conversions in C++. A program with the line char *buffer = malloc(10 * sizeof(char)); would compile in C, but fail to compile in C++, where you'd need to cast the malloc to char *. public headers for C libraries also need to wrap functions with extern "C" when compiled in C++, so the linker does not assume the functions have a C++ API with name mangling to support function overloading.
Yes, there are ways to modify C code to compile under C++. The point was that C++ is not a proper superset of C and there are valid C programs that do not compile under strict C++.
No C++ compiler will compile this because the example makes no sense. Not sure what’s the point you’re trying to make. And your second example works exactly as intended, since X is redefined inside main and hides global scope char X.
The comment I replied to asked: "Don't C programs compile unmodified with a C++ compiler?"
I gave a concrete example of a C program that does not compile as C++, i.e. my answer is "no".
I also gave an example of a C program that compiles as C++, but behaves differently at runtime, proving that C++ is not a superset of C even if you only consider programs that are valid in both languages.
Normally not, but the only common incompatibility is in the return type of malloc (although it's void * in both C and C++, void * has a different meaning in the two languages). Once you've worked around that, a typical C program is quite likely to compile as C++.
There are plenty of other incompatibilities that could happen in theory, but they rarely come up in practice.
3
u/ThirdEncounter May 01 '18 edited May 02 '18
Don't C programs compile unmodified with a C++ compiler?
Edit: So the consensus is, not except for specific cases. Thanks, all.