Skip to the workspace
Pebellslearn by building
Introduction to C  ›  Lesson

C vs C++

C vs C++ 10 minC++ began as an extension of C and shares its syntax, but it is a separate language with classes, templates and automatic cleanup, and not every valid C program is valid C++.

c / C vs C++

Explore each scene at your own pace.

01 · The rule

The rule

C vs C++

C++ began as an extension of C and shares its syntax, but it is a separate language with classes, templates and automatic cleanup, and not every valid C program is valid C++.

Distinguish the languages' shared syntax from rules and libraries that differ.

Job adverts often ask for "C/C++", as if it were one language. The two share a history and much of their syntax, yet a program written in the natural style of one looks very different in the other. Knowing where they part ways stops you from mixing their habits.

The rule

C++ grew out of C, but it is a different language, not a bigger C.

In 1979 Bjarne Stroustrup began "C with Classes", renamed C++ in 1983. Today each language has its own ISO standard and its own committee.

C++ adds a great deal on top of C's ideas:

  • Classes with member functions, constructors and destructors
  • Templates for writing code once for many types
  • Exceptions, references, function overloading and namespaces
  • A large standard library: std::vector, std::string, std::map
  • Destructors that release resources automatically when an object goes out of scope

C stays small: functions, structs, pointers, manual memory management and a compact standard library.

Here is the same idea, "keep 24 hourly readings", in each language. First C, inside a function:

#include <stdlib.h>

double *hourly = malloc(24 * sizeof *hourly);   /* ask for 24 slots */
/* ... fill and use them ... */
free(hourly);                                    /* give them back yourself */

And the C++ way:

#include <vector>

std::vector<double> hourly(24);   // can grow, and frees itself

C is not a strict subset of C++. Some valid C is rejected by a C++ compiler:

  • int new = 5; is fine in C, but new is a keyword in C++.
  • Assigning malloc's result to a double * without a cast is fine in C, but C++ demands the cast.
  • In C a character constant such as 'A' has type int, so sizeof('A') equals sizeof(int). In C++ it has type char, so the answer is 1.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.