</>EmbeddedInterview

What is the difference between C and C++ for embedded systems?

EasyC++ for Embedded

Short answer: C++ adds classes, templates, references, RAII, constexpr, namespaces, stronger type checking and a large standard library on top of (mostly) C. Most of these are zero-cost abstractions: they generate the same machine code as careful C. The features with run-time cost or non-determinism — exceptions, RTTI, dynamic allocation, and some standard containers — are usually disabled or avoided on microcontrollers. Used as "a better C with zero-cost abstractions", C++ produces code that is as small and fast as C but safer and easier to maintain.

Feature Cost on an MCU Typical policy
Classes, inheritance (non-virtual), namespaces, references none use
constexpr, templates, enum class, std::array, std::span none at run time (templates may grow code) use, watch code size
Virtual functions vtable pointer per object, indirect call use where runtime polymorphism is needed
RAII (constructors/destructors) none beyond the code you'd write anyway use
Lambdas none (unless stored in std::function) use
Exceptions unwind tables, larger code, non-deterministic timing usually disabled (-fno-exceptions)
RTTI (dynamic_cast, typeid) type info tables usually disabled (-fno-rtti)
new/delete, std::vector, std::string, std::map heap use, fragmentation avoid after start-up; use fixed-capacity containers or pools
<iostream> very large code size avoid; use snprintf or a small formatter

Practical differences when switching

  • Name mangling: C++ function names are mangled, so C headers need extern "C".
  • Stricter rules: no implicit conversion from void *, designated initialisers only from C++20 (and in declaration order), no VLAs, different const linkage.
  • Start-up code must run global constructors (__libc_init_array calls .init_array).
  • Guidelines: MISRA C++:2023, AUTOSAR C++14 and the C++ Core Guidelines define safe subsets.

Interview line: "I use C++ for type safety and abstraction without overhead: classes for drivers, templates and constexpr for configuration, RAII for locks and critical sections; I disable exceptions and RTTI and avoid heap allocation after initialisation."