C primer for C++ programmers

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

# C primer for C++ programmers

Sep 2009

I've never learnt pure C programming language, only C++. It does not mean I never use global variables or fopen function, but I it makes no sense for me to code in pure C when there is a C++ compiler available. But today I've decided to skim the classic book "The C Programming Language" by Brian W. Kernighan and Dennis Ritchie. Here is what I've found out:

You can actually code in C using Visual C++. To do this, you need to: (+) Create empty project, (+) Add a file with .c extension, (+) Enter project options, (+) Nagivate to Configuration Properties / C/C++ / Advanced, (+) Set "Compile As" to "Compile as C Code (/TC)".

The C language is similar to C++ except it lacks features such as:

There are some differences between C++ and C though. For example, you don't have to state type of function parameter or return type if you want to it to default to int. Following lines are equivalent:

int MyFunc1(int a, int b) { }
MyFunc2(a, b) { }

Compiler is generally more liberal when it comes to type checking and function calling. You can call function with more arguments than expected and it only generates warning. You can declare function with empty parameter list like MyFunc() which means unknown parameter list! To explicitly state that a function takes 0 parameters you have to write MyFunc(void).

Local variables can be defined only before any other statements in a block. You also cannot define a variable inside for loop. Example:

void Func(void)
  int a = 1; // OK
  int b = 2; // Error!
    int c = 3; // OK

C requires different syntax for using structures. If you define a structure like this:

struct Struct1 { int x; };

You have to prefix the name of this type with "struct" keyword each time you use it, just like this:

struct Struct1 *myObj;

But luckily typedef construct works in C, so the common solution to this problem is to use it like this:

typedef struct { int x; } Struct1;
Struct1 *myObj;

Comments | #c++ #c #visual studio Share


[Stat] [STAT NO AD] [Download] [Dropbox] [pub] [Mirror]
Copyright © 2004-2017