Juha Nieminen <nos...@thanks.invalid> writes:
> Some people often object if someone conflates C and C++, as if C++ were
> just a pure superset of C, pointing out that they are, in fact, different
> languages and, in some aspects, actually incompatible with each other.
>
> That got me thinking: What are all the differences between the two
> languages, in behavior and meaning, when it comes to their common
> syntax?
Let's see...
"abc" is of type char * in C and of type const char * in C++.
Then there all the keyword differences. For example, in C, new is an
ordinary ID and in C++ restrict is an ordinary ID. There are quite a
few of these!
The rules for compatible pointer types are stronger in C++. Basically,
you can only add a top-level const when passing arguments in C.
In C++ function declarations, () means (void), but in C it means an
old-style function with unspecified arguments.
In C, at file scope, int x[]; is a "tentative definition" (which will
resolve to int x[] = {0}; if there are no further declarations of x) but
in C++ it's just an error.
In C, f( (int[]){1} ), calls f with a temporary array (it's a "compound
literal"), but that's forbidden in C++.
Some things that are compound literals in C /are/ valid in C++. For
example:
struct s { int v; };
...
f((struct s){1});
is ok in both, but add a pointer and you get the same difference as
above:
g(&(struct s){1}); // ok in C, not ok in C++
And now I'm out of time...
> In other words, I'm not here talking about different keywords and different
> syntax that compiles in one but not the other. I'm talking about code that
> does compile as both C and C++, but will be interpreted or behave
> differently depending on which (and this makes them incompatible).
>
> Here are some of the things that come to mind. What other things are there?
>
> 1) A 'const' variable at the global scope will have external linkage by
> default in C (unless explicitly made to have internal linkage with
> 'static'), but internal linkage by default in C++ (unless explicitly made
> to have external linkage with 'extern').
>
> 2) The type of 'A' is int in C, but char in C++.
>
> 3) This one is really obscure: In C, this:
>
> int f(int (*)(), double (*)[3]);
> int f(int (*)(char *), double (*)[]);
>
> is a valid function declaration, and equivalent to:
>
> int f(int (*)(char *), double (*)[3]);
Yes. This is C's rules for "composite types" in action.
> (This one is so obscure that I'm certain the vast majority of C programmers,
> even experienced ones, would be surprised it even compiles. However, the
> example is directly from the C standard, so it's pretty legit.)
>
> In C++ the two first lines declare two different functions, taking different
> types of parameter. Calling one is not the same thing as calling the
> other.
However, you can, in fact call the second f with a double (*)[] argument
because of C++'s rules about similar types (at least I think those are
the rules that apply here).
--
Ben.