The comment to this answer got me wondering. I\'ve always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension. Am I wrong a
A couple of other things that are valid C but not C++:
int func();
func(0,0); //Error in C++, but not in C
Also don't underestimate the impact of C++ having more keywords:
int new; //Obviously an error in C++
typedef struct {
int a, b, c;
} st;
st s = {
.a = 1,
.b = 2,
};
This is valid C code which does not compile in most C++ compilers. It is not part of the C++ spec as far as I know. However, some C++ compilers are "liberal" with certain parts of the language and allow things they shouldn't, just as a lot miss out on a few nuances that are in the spec but almost never used.
One thing that sets the two apart and comes up in day to day development is linkage and function name mangling. A C function compiled with a C compiler is not accessible to C++ unless the prototype is marked up with extern "C"
.
In general, yes C code is considered C++ code.
But C is not a proper subset in a strict sense. There are a couple of exceptions.
Here are some valid things in C that are not valid in C++:
int *new;//<-- new is not a keyword in C
char *p = malloc(1024); //void * to char* without cast
There are more examples too, but you get the idea.
I previously wrote a more extensive answer in a similar question here.
A few more:
C allows recursive calls to main, C++ does not
char foo[3] = "abc"
is legal C, not C++
sizeof('A') == sizeof(int)
is true in C and false in C++
There are even more changes with C99
Edit: I found a post that lists the majority of the differences. http://c-faq.com/misc/cplusplus.nr.html
Summary of why C is not proper subset of C++:
void *
to any object/incomplete typestruct
s becoming scopedstruct
tags becoming typedef
sint
rulesmain
//
commentschar
and not int
etc. Also note that C99 adds several features which aren't permitted in C++ (or are only supported using vendor extensions), such as builtin _Complex
and _Imaginary
data types, variable-length arrays (arrays sized at runtime rather than compile time), flexible array members (arrays declared as the last member of a struct that may contain an unspecified number of elements), and more.
For the exhaustive list of incompatibilities between C and C++, including changes with C99, see http://david.tribble.com/text/cdiffs.htm.