C vs C++
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 itselfC is not a strict subset of C++. Some valid C is rejected by a C++ compiler:
int new = 5;is fine in C, butnewis a keyword in C++.- Assigning
malloc's result to adouble *without a cast is fine in C, but C++ demands the cast. - In C a character constant such as
'A'has typeint, sosizeof('A')equalssizeof(int). In C++ it has typechar, so the answer is 1.
The shortcut
Scan a snippet for tell-tale signs. Any of class, template, std::, new/delete, cout << or namespace means C++. Code with only struct, malloc/free, printf and plain functions could be either, and is most likely C.
Read the includes
#include <stdio.h>works in both.#include <vector>or<iostream>means C++.
Drills
Answer fast — trust the rule.
Which line is valid C but an error in C++?
Which feature does C++ have that C lacks?
In C, what is sizeof('A') equal to?
A snippet uses std::vector<double> and cout << avg;. Which language is it?
Remember
- C++ grew out of C, but it is a different language, not a bigger C.
- Shortcut:
class,template,std::,new,coutmean C++; plain structs,mallocandprintfpoint to C. - Trap: C is not a strict subset of C++. Keywords, casts and
sizeof('A')differ.
