C vs C++
Rocket Run's sound code came from an old C library, and your new code is C++. Can they live in one project? Mostly yes, because C++ was built on top of C. Knowing exactly where the two differ tells you which old habits to keep and which to upgrade.
The rule
C++ keeps C's core and adds classes, references, templates and a library.
Nearly every C feature exists in C++: the same int, if, for, functions, pointers and structs. What C++ adds:
- Classes with constructors and destructors, so objects set themselves up and clean up after themselves.
- References, a safer alternative to many pointer uses.
- Function overloading: two functions may share a name if their parameters differ.
- Templates, so one piece of code works for many types.
- A large standard library:
std::string,std::vector, algorithms and more.
The same task in both languages:
/* C */
char name[32];
strcpy(name, "Nova");
int *scores = malloc(10 * sizeof(int));
/* ... */
free(scores);// C++
std::string name = "Nova";
std::vector<int> scores(10);
// both clean up automatically at the end of the scope"Mostly compatible" is not "fully compatible". The malloc line above is valid C but an error in C++, because C++ will not silently convert the untyped void* that malloc returns into an int*. C code that uses a C++ keyword such as class or new as a variable name also fails.
The shortcut
Whenever you reach for a C tool, ask for its C++ upgrade:
| C habit | C++ upgrade |
|---|---|
char name[32] |
std::string |
malloc / free |
std::vector, or std::make_unique |
#define MAX_LIVES 3 |
constexpr int max_lives = 3; |
printf |
std::cout, or std::format in C++20 |
| pointer used to change an argument | reference parameter |
Spot the C habit
The C version stores the name in
char name[32]and copies it withstrcpy. A 40-character name would overflow.
Drills
Answer fast — trust the rule.
Which line is valid C but an error in C++?
What is the C++ upgrade for storing a player name in char name[32]?
Which feature does C++ have that C lacks?
Why prefer constexpr int max_lives = 3; over #define MAX_LIVES 3?
Remember
- C++ keeps C's core and adds classes, references, templates and a library.
- Shortcut: for each C habit, reach for its C++ upgrade.
- Trap: most C compiles as C++, but not all;
mallocwithout a cast is the classic example.
