Skip to content
Tutorials Center
My learning

Topics

Lesson 149 of 171 ยท Modern C++ and Beyond

C and C++: Differences and Interoperability

How C and C++ differ - what C++ added, valid C that C++ rejects, printf vs std::print, malloc vs new - and how to call C libraries with extern "C" safely.

C++ began in 1979 as "C with Classes", and it still compiles most C code with few or no changes. That heritage is one of its biggest strengths: the operating system APIs, databases, compression libraries, graphics drivers and embedded SDKs you'll use are very often written in C, and C++ can call them directly, with no wrappers or bindings in between. But C and C++ are separate languages with separate standards (the latest are C23 and C++23). They've diverged in ways that matter, and code that's perfectly correct C can be invalid, or subtly different, in C++.

This lesson shows what C++ added on top of C, the C code that C++ rejects or treats differently, how C-style I/O and memory management compare with their C++ counterparts, and how to mix the two languages in one program: extern "C", C-compatible headers, wrapping C resources in RAII types, and exposing a C++ library through a C interface. The examples marked c run with gcc -std=c23; the others are C++23 as usual.

What C++ added

Almost everything this course covered beyond the basics is C++-only. C has functions, structs, pointers, arrays, malloc and the preprocessor; C++ adds:

Area C++ features with no C equivalent
Abstraction classes, access control, constructors and destructors (RAII), inheritance, virtual functions
Generic code templates, concepts, auto deduction for functions and lambdas
Safety and errors references, exceptions, std::unique_ptr/shared_ptr, const member functions, scoped enum class
Organization namespaces, function and operator overloading, modules
Library containers, algorithms, ranges, std::string, std::format/std::print, threads and atomics as part of a large standard library

C hasn't stood still either. C23 adopted several ideas from C++: bool, true and false are now keywords, nullptr exists, constexpr works for objects, auto can deduce a variable's type, typeof arrived, [[nodiscard]]-style attributes work, and int f() finally means "no parameters", exactly as in C++. The languages are closer today than they were twenty years ago, but the core difference remains: C gives you a small language and expects you to manage everything by hand; C++ gives you tools to make the compiler manage it for you.

C Modern C23 looks familiar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

There are no classes, no std::string and no std::print: names are const char*, the array has a fixed size, and output goes through printf. Every C feature used here also exists in C++, with the same or very similar meaning.

Valid C that isn't valid C++

C++ is not a strict superset of C. The differences you'll actually hit when compiling C code as C++:

  • void* doesn't convert implicitly. In C, int *p = malloc(n * sizeof *p); is idiomatic. C++ requires a cast, because an implicit conversion from void* would defeat type checking.
  • New keywords. class, new, delete, template, this, namespace, operator, private and others are fine identifiers in C and errors in C++.
  • Designated initializers are stricter. C accepts them in any order, nested, and for array elements ([3] = 7). C++20 requires declaration order and doesn't allow array designators.
  • String literals are const. In C, char *s = "hello"; compiles (writing through it is still undefined). In C++ a string literal is const char[N], so you need const char*.
  • Character literals have different types. 'a' is an int in C but a char in C++, which matters for sizeof and for overloading.
  • Enums are real types in C++. C lets you assign any int to an enum variable; C++ requires a cast.
  • Variable-length arrays (int buf[n]; with a runtime n) are optional in C and not part of C++ at all (GCC accepts them as an extension; use std::vector).
  • restrict, _Generic and compound literals such as (struct point){1, 2} are C features; C++ has no restrict keyword and uses templates and overloading instead of _Generic.
  • Linkage of const globals. A namespace-scope const int limit = 10; has internal linkage in C++ (each file gets its own) but external linkage in C.
  • goto and switch can't jump over initializations in C++; C allows it for most variables.
C C code that a C++ compiler rejects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In C, sizeof('a') is 4 on our server, the size of an int. Here's the same program made valid C++, with every change marked:

C++ The same program as C++

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output is identical except for the last number: sizeof('a') is 1 in C++. This is still C-style code, of course. Real C++ would use std::vector<int>, std::array and std::println, which is what the rest of this lesson argues for. Note the headers: C++ provides every C header in two forms, <stdio.h> (names in the global namespace) and <cstdio> (names in std::, usually also global). Prefer the <c...> forms in C++ code.

printf and scanf versus streams and std::print

C formats text with printf and parses it with scanf. Both use a format string whose conversion specifiers (%d, %s, %f, %zu) must match the argument types exactly, and the compiler can't enforce that in general: a mismatch such as printf("%d", 3.5) is undefined behavior. GCC and Clang check literal format strings with -Wformat (part of -Wall), which helps, but nothing stops a mismatch in a format string built at run time. scanf("%s", buffer) with no width limit is a classic buffer overflow.

C Reading and printing in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C++ replaced this twice. iostreams (std::cin >>, std::cout <<) pick the right conversion from the argument's type, so mismatches can't happen, and they work with user-defined types via operator<< (see I/O Streams in Depth). std::format and std::print (C++20/23) bring back the convenience of format strings but check them at compile time against the argument types (see Formatting with std::format and std::print):

C++ The C++ version, checked by the compiler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Both programs print the same table. The C++ one can't overflow its buffer, can't mismatch a type, and would reject a bad format specifier before the program ever runs. printf remains useful when you write C or call C APIs that take format strings, such as snprintf; with std::format available, there's little reason to use it in new C++ code.

malloc and free versus new, delete and containers

malloc returns raw, uninitialized bytes. It knows nothing about types, so it never runs a constructor, and free never runs a destructor. In C that's fine, because C structs have no constructors. In C++ it means malloc is only safe for trivial types (plain ints, doubles, C-style structs), and even then you must call it with the right size and cast the result. new allocates and constructs; delete destroys and frees. The pairs must never be mixed: freeing newed memory with free, or deleteing malloced memory, is undefined behavior.

C++ malloc doesn't construct, new does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C's growable array, built with realloc, is a good illustration of what std::vector does for you:

C
int *data = NULL;
size_t size = 0, capacity = 0;

void push(int value) {
    if (size == capacity) {
        size_t new_capacity = capacity ? capacity * 2 : 4;
        int *bigger = realloc(data, new_capacity * sizeof *bigger);
        if (bigger == NULL) { /* handle out of memory; data is still valid */ }
        data = bigger;
        capacity = new_capacity;
    }
    data[size++] = value;
}
/* ... and remember free(data) on every exit path */

realloc may move the block by copying bytes, which is only correct for trivially copyable types; std::vector moves or copies its elements with their constructors instead, and its destructor frees the memory automatically (see std::vector in Depth and Dynamic Memory: new and delete).

extern "C" and name mangling

To support overloading, a C++ compiler encodes each function's parameter types into its symbol name. GCC turns double area(double, double) into the symbol _Z4areadd; a C compiler just emits area. This is called name mangling, and it's why a C++ file that declares a C function the normal way fails to link: it looks for the mangled name, which the C library doesn't contain.

TEXT
$ nm geometry.o              (symbols in an object file)
0000000000000000 T _Z4areadd     double area(double, double), compiled as C++
0000000000000020 T polygon_area  extern "C" double polygon_area(...)

extern "C" tells the C++ compiler to use C linkage for a declaration: no mangling, and the platform's C calling convention. As a consequence, extern "C" functions can't be overloaded. Headers meant for both languages use the __cplusplus macro, which only C++ compilers define:

C
/* geometry.h - usable from C and C++ */
#ifndef GEOMETRY_H
#define GEOMETRY_H

#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

double polygon_area(const double *xs, const double *ys, size_t count);

#ifdef __cplusplus
}
#endif

#endif

The C standard library headers already do this, which is why you can call strlen, qsort or fopen from C++ without thinking about it. Most popular C libraries (SQLite, zlib, libcurl, OpenSSL, SDL) ship headers with the same guard. If you meet an old header that doesn't, wrap the include yourself: extern "C" { #include "old.h" }, with the #include on its own line.

Calling C libraries from modern C++

C APIs are built around raw pointers, output parameters, error codes, errno and pairs of "create/destroy" functions. Calling them works out of the box; using them well means wrapping those habits in C++ types:

  • Give every C resource an owner: std::unique_ptr with a custom deleter turns fopen/fclose, sqlite3_open/sqlite3_close or malloc/free into RAII.
  • Pass std::string::c_str() or data() to functions that read strings, and std::vector<T>::data() plus size() where an API wants a pointer and a length.
  • Convert error codes to exceptions or std::expected at the boundary, so the rest of your code never sees errno.
  • Callbacks passed to C must be plain functions or captureless lambdas (they convert to function pointers); use the API's void* "user data" argument to reach your C++ objects.
C++ Wrapping C APIs in C++ types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The 20-digit number overflows long, so strtol sets errno to ERANGE and parse_long returns empty. In C++ code you'd normally reach for std::from_chars and std::ranges::sort instead (see Converting Between Strings and Numbers); the point here is the technique for the many C APIs that have no C++ replacement.

Exposing C++ through a C interface

The reverse direction matters too. The C ABI is stable and understood by every language (Python, Rust, C#, Go and Java can all call C functions), while the C++ ABI differs between compilers and even between standard library versions. So libraries written in C++ often publish a C interface: an opaque handle type, extern "C" functions to create, use and destroy it, and error codes instead of exceptions. Two rules make this safe: no exception may escape an extern "C" function (C callers can't handle one), and no C++ types (std::string, references, templates) may appear in the signatures.

C++ A C API implemented in C++

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Inside the implementation you're free to use any C++ you like; only the boundary looks like C. C++ callers can then wrap the handle back into a std::unique_ptr<word_list, Deleter>, exactly like the FILE* example.

Two more boundary rules: never use setjmp/longjmp across C++ frames, because longjmp skips destructors, and keep allocation and deallocation on the same side. Memory returned by a C library must be released with that library's free function, and memory from new must never be handed to C code that calls free.

When to choose C, and when C++

C is still the right tool when you need the smallest possible runtime, a compiler for an obscure microcontroller, a stable ABI for a library used from many languages, or when a project (the Linux kernel, many embedded codebases) is already C. C++ is the better choice almost everywhere else you'd consider C: it compiles to equally fast code, and RAII, containers, templates and std::print remove whole classes of bugs that C programmers must avoid by discipline. And thanks to extern "C", you never have to choose for your dependencies: C++ programs use C libraries every day.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int *p = malloc(10 * sizeof *p); compiles as C. What happens when you compile it as C++?

    C++ removed the implicit conversion from void* to other object pointer types. You need static_cast<int*>(...), and in real C++ you'd use std::vector<int> instead.
  2. 2. What does printf("%zu", sizeof('a')) print on a typical 64-bit system, in C and in C++?

    A character literal has type int in C, so its size is sizeof(int), usually 4. In C++ it has type char, whose size is always 1.
  3. 3. Why does a C++ program fail to link when it declares a C library function without extern "C"?

    C++ encodes parameter types into symbol names to support overloading. extern "C" switches the declaration to C linkage, so the linker looks for the unmangled name the C compiler produced.
  4. 4. A C++ library exposes extern "C" int lib_parse(const char* text); and its implementation can throw std::bad_alloc. What should it do?

    C callers can't catch C++ exceptions, so letting one escape is not an option. Catch everything at the boundary and translate it into an error code; std::expected isn't a C type.
  5. 5. Memory for a struct with a std::string member was obtained with malloc. What is wrong?

    malloc returns raw bytes. Types with constructors need new (or a container or make_unique), which allocates and constructs; free likewise never runs destructors.

Summary

  • C++ grew out of C and can call C code directly, but they're separate languages; C23 has adopted bool, nullptr, constexpr objects, auto and attributes from C++.
  • Valid C that C++ rejects: implicit void* conversion, C++ keywords as names, out-of-order or array designators, non-const pointers to string literals, VLAs; 'a' is an int in C and a char in C++.
  • printf/scanf trust the format string; iostreams and std::print are type-safe, and std::format strings are checked at compile time.
  • malloc/free handle raw bytes and never run constructors or destructors; never mix them with new/delete, and prefer containers and smart pointers.
  • extern "C" disables name mangling; shared headers wrap declarations in #ifdef __cplusplus guards.
  • Wrap C resources in std::unique_ptr with custom deleters, convert error codes at the boundary, and pass captureless lambdas as callbacks.
  • To expose C++ to other languages, publish an opaque handle with extern "C" functions, and never let exceptions or C++ types cross the boundary.

Next: Project: Grade Book, the first hands-on project, which puts vectors, algorithms and std::print to work on real input.