What are the incompatible differences between C(99) and C++(11)?

C++CC++11C99

C++ Problem Overview


This question was triggered by replie(s) to a post by Herb Sutter where he explained MS's decision to not support/make a C99 compiler but just go with the C(99) features that are in the C++(11) standard anyway.

One commenter replied:

> (...) C is important and deserves at least a little bit of attention. > > There is a LOT of existing code out there that is valid C but is not > valid C++. That code is not likely to be rewritten (...)

Since I only program in MS C++, I really don't know "pure" C that well, i.e. I have no ready picture of what details of the C++-language I'm using are not in C(99) and I have little clues where some C99 code would not work as-is in a C++ compiler.

Note that I know about the C99 only restrict keyword which to me seems to have very narrow application and about variable-length-arrays (of which I'm not sure how widespread or important they are).

Also, I'm very interested whether there are any important semantic differences or gotchas, that is, C(99) code that will compile under C++(11) but do something differently with the C++ compiler than with the C compiler.


Quick links: External resources from the answers:

C++ Solutions


Solution 1 - C++

There are a bunch of incompatibilities that have been around for ages (C90 or earlier), as well as a bunch of really nice features in C99 and C11. These are all off the top of my head.

// Valid C
int *array = malloc(sizeof(*array) * n);

// Valid C and valid C++, extra typing, it's always extra typing...
int *array = (int *) malloc(sizeof(*array) * n);

// Valid C++
int *array = new int[n];

C99 is nice and C programmers everywhere should use it

The new features in C99 are very nice for general programming. VLAs and restrict are not (in my opinion) targeted for general use, but mostly for bringing FORTRAN and numerical programmers to C (although restrict helps the autovectorizer). Since any conforming program that uses restrict will still work exactly the same way (but possibly not as fast) if you #define restrict at the top of the file, it's not a big deal. VLAs are pretty rare in the wild it seems.

Flexible array members can be nice. Note that these are NOT the same as variable-length arrays! People have been using this trick for years, but official support means less typing and it also allows us to make constants at compile time. (The old way was to have an array of size 1, but then computing the allocation size is a real bother.)

struct lenstr {
    unsigned length;
    char data[];
};
// compile time constant
const struct lenstr hello = { 12, "hello, world" };

Designated initializers. Saves a lot of typing.

struct my_struct { int a; char *b; int c; const char *d; };
struct my_struct x = {
    .a = 15,
    .d = "hello"
    // implicitly sets b = NULL and c = 0
};
int hex_digits[256] = { ['0'] = 0, ['1'] = 1, ['2'] = 2, /* etc */ ['f'] = 15 };

The inline keyword behaves differently, you can choose which translation unit gets a non-inline version of a function declared inline by adding an extern declaration to that unit.

Compound literals.

struct point { float x; float y; };
struct point xy_from_polar(float r, float angle)
{
    return (struct point) { cosf(angle) * r, sinf(angle) * r };
}

The snprintf function is probably in my top 10 most useful library functions in C. It's not only missing from C++, but the MSVC runtime only provides a function called _snprintf, which is not guaranteed to add a NUL terminator to the string. (snprintf is in C++11, but still conspicuously absent from the MSVC C runtime.)

Anonymous structures and unions (C11, but GCC extension since forever) (anonymous unions are apparently in C++03, no MSVC support in C mode):

struct my_value {
    int type;
    union {
        int as_int;
        double as_double;
    }; // no field name!
};

As you can see, many of these features just save you a lot of typing (compound literals), or make programs easier to debug (flexible array members), make it easier to avoid mistakes (designated initializers / forgetting to initialize structure fields). These aren't drastic changes.

For semantic differences, I'm sure the aliasing rules are different, but most compilers are forgiving enough these days I'm not sure how you'd construct a test case to demonstrate. The difference between C and C++ that everyone reaches for is the old sizeof('a') expression, which is always 1 for C++ but usually 4 on a 32-bit C system. But nobody cares what sizeof('a') is anyway. However, there are some guarantees in the C99 standard that codify existing practices.

Take the following code. It uses a common trick for defining union types in C without wasting extra storage. I think this is semantically valid C99 and I think this is semantically dubious C++, but I might be wrong.

#define TAG_FUNKY_TOWN 5
struct object { int tag; };
struct funky_town { int tag; char *string; int i; };
void my_function(void)
{
    struct object *p = other_function();
    if (p->tag == TAG_FUNKY_TOWN) {
        struct funky_town *ft = (struct funky_town *) p;
        puts(ft->string);
    }
}

It's a shame, though. The MSVC code generator is nice, too bad there's no C99 front-end.

Solution 2 - C++

If you start from the common subset of C and C++, sometimes called clean C (which is not quite C90), you have to consider 3 types of incompatibilities:

  1. Additional C++ featues which make legal C illegal C++

Examples for this are C++ keywords which can be used as identifiers in C or conversions which are implicit in C but require an explicit cast in C++.

This is probably the main reason why Microsoft still ships a C frontend at all: otherwise, legacy code that doesn't compile as C++ would have to be rewritten.

  1. Additional C features which aren't part of C++

The C language did not stop evolving after C++ was forked. Some examples are variable-length arrays, designated initializers and restrict. These features can be quite handy, but aren't part of any C++ standard, and some of them will probably never make it in.

  1. Features which are available in both C and C++, but have different semantics

An example for this would be the linkage of const objects or inline functions.

A list of incompatibilities between C99 and C++98 can be found here (which has already been mentioned by Mat).

While C++11 and C11 got closer on some fronts (variadic macros are now available in C++, variable-length arrays are now an optional C language feature), the list of incompatibilities has grown as well (eg generic selections in C and the auto type-specifier in C++).

As an aside, while Microsoft has taken some heat for the decision to abandon C (which is not a recent one), as far as I know no one in the open source community has actually taken steps to do something about it: It would be quite possible to provide many features of modern C via a C-to-C++ compiler, especially if you consider that some of them are trivial to implement. This is actually possible right now using Comeau C/C++, which does support C99.

However, it's not really a pressing issue: Personally, I'm quite comfortable with using GCC and Clang on Windows, and there are proprietary alternatives to MSVC as well, eg Pelles C or Intel's compiler.

Solution 3 - C++

In C++, setting one member of a union and accessing the value of a different member is undefined behavior, whereas it's not undefined in C99.

There are lots of other differences listed on the wikipedia page.

Solution 4 - C++

I will mention "C.1 C++ and ISO C" of the C++11 standard. That document has a blow by blow of each difference and its impact on development.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin BaView Question on Stackoverflow
Solution 1 - C++Dietrich EppView Answer on Stackoverflow
Solution 2 - C++ChristophView Answer on Stackoverflow
Solution 3 - C++bames53View Answer on Stackoverflow
Solution 4 - C++emsrView Answer on Stackoverflow