C and C++ compiler difference in action

So before Visual Studio have a C99 compiler, I use C++98 compiler for my C code. You just rename .c to .cpp and it compiles fine, at least most of the time. Since C++ is actually not a super set of C(read http://david.tribble.com/text/cdiffs.htm), sometimes C++ compiler can’t handle legit C code.

A common one is type casting. You can do this in C:

int *foo = malloc(16 * sizeof(int));

But in C++, you have to cast the pointer, like this:

int *foo = (int *)malloc(16 * sizeof(int));

Another I encountered is struct initialization. Suppose you got this struct:

struct foo {
 int gee;
 float bar;
};

in C, you can initialize a variable like this:

struct foo a = {
 .gee = 1,
 .bar = 0.1f
};

in C++, member name notation with . is not allowed, you need to use this:

struct foo a = {
 1,
 0.1f;
};

but notation in C is more intuitive, if you miss that in C++, use this:

struct foo a = {
 /* .gee = */ 1,
 /* .bar = */ 0.1f
};

Another interesting thing is C89 has no “inline” keyword but C++98 can handle that well.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s