Category Archives: compiler

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, 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 = {

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.