Back to series
· 10 min read

The Difference Between C and C++


I. The Basic Positioning of C and C++

C and C++ are both programming languages widely used in system software, low-level development, and high-performance computing. The two share a similar syntactic foundation, but there are clear differences in their design goals, language mechanisms, and engineering capabilities.

1. The C Language

C was designed by Dennis Ritchie in the early 1970s, originally for Unix system development.

The core design goals of C include:

  • Close to the hardware: provides pointers, memory addresses, and low-level data manipulation capabilities.
  • Efficient execution: few language abstractions, making it easy for compilers to generate efficient machine code.
  • Structured programming: organizes programs around functions, statements, and control structures.
  • Portability: supports different hardware and operating systems through a standardized language specification.

C is commonly used for:

  • Operating system kernels
  • Embedded systems
  • Device drivers
  • Compilers and interpreters
  • Network protocol stacks
  • System-level tools

2. The C++ Language

C++ was designed by Bjarne Stroustrup in the early 1980s, initially based on C with Classes and later developed into a multi-paradigm programming language.

C++ retains a large amount of C-style syntax while adding richer abstraction mechanisms.

Its core design capabilities include:

  • Object-oriented programming: classes, objects, inheritance, polymorphism, and encapsulation.
  • Generic programming: templates, type parameters, and compile-time computation.
  • Resource management: constructors, destructors, and RAII.
  • Operator overloading: allows user-defined types to define specific operation behavior.
  • Standard library: provides containers, algorithms, iterators, concurrency tools, and more.
  • Zero-cost abstraction: provides high-level abstraction capabilities without runtime overhead.

C++ is commonly used for:

  • Game engines
  • Desktop applications
  • High-performance servers
  • Browsers and databases
  • Graphics rendering
  • Financial computing
  • Real-time systems

II. The Core Differences Between C and C++

The difference between C and C++ is not just whether classes exist; the two languages differ systematically in their approach to abstraction, type systems, resource management, and program organization.

Comparison Dimension C C++
Programming paradigm Mainly procedural programming Multi-paradigm programming
Core organizational approach Functions, structs Classes, objects, functions, templates
Object orientation Not natively supported Natively supported
Encapsulation mechanism Achieved through structs and module conventions Classes, access control, and encapsulation
Inheritance and polymorphism Not natively supported Supports inheritance and runtime polymorphism
Generic mechanism Mainly relies on macros, void*, etc. Templates
Function overloading Not supported Supported
Operator overloading Not supported Supported
Memory management malloc, free new, delete, and RAII
Resource management Mainly relies on explicit release and conventions Constructors, destructors, and smart pointers
Exception handling No language-level exception mechanism Supports exception mechanisms
Standard library Relatively minimal Provides a rich standard library
Type system Based on C's type rules Adds mechanisms such as classes, templates, and references
Compilation complexity Relatively low Usually more complex
Binary compatibility Depends on the ABI and platform Also involves name mangling, object layout, etc.

Note: C++ is not simply C with object-oriented features added. C++ has its own independent language standard, and the syntax and semantics of C and C++ are not fully compatible.

III. Differences in Programming Paradigm

1. C: Procedural programming at its core

C typically organizes a program into multiple functions, completing business logic through function calls.

Data structures and the functions that operate on that data are usually defined separately.

#include <stdio.h>

struct User {
    int id;
    int age;
};

void print_user(struct User user) {
    printf("ID: %d, Age: %d\n", user.id, user.age);
}

int main(void) {
    struct User user = {1, 25};

    print_user(user);

    return 0;
}

In this example:

  • struct User describes the data structure.
  • print_user() is responsible for manipulating and displaying the data.
  • The data and the functions that operate on it are not bound together through a language-level class mechanism.

C can achieve reasonably good encapsulation through modules, header files, structs, and function pointers, but developers must design the interface boundaries themselves.

2. C++: Supports object-oriented programming

C++ can organize data and the methods that operate on that data within the same class.

#include <iostream>
#include <string>

class User {
private:
    int id;
    int age;

public:
    User(int userId, int userAge)
        : id(userId), age(userAge) {}

    void print() const {
        std::cout << "ID: " << id
                  << ", Age: " << age << '\n';
    }
};

int main() {
    User user(1, 25);

    user.print();

    return 0;
}

Here:

  • private controls member access permissions.
  • The constructor is responsible for initializing the object.
  • print() is a method of the object.
  • A const member function promises not to modify the object's non-mutable members through that function.

C++'s class mechanism can encapsulate data and behavior together, but it does not mean that all C++ programs must adopt object-oriented design.

C++ also supports procedural programming and functional-style programming.

IV. Differences Between Data Types and Type Systems

1. Differences in Structs

Both C and C++ support structs, but structs in C++ have richer capabilities.

C:

struct Point {
    int x;
    int y;
};

int main(void) {
    struct Point p = {10, 20};

    return 0;
}

C++:

struct Point {
    int x;
    int y;

    void move(int dx, int dy) {
        x += dx;
        y += dy;
    }
};

int main() {
    Point p{10, 20};

    p.move(5, 5);

    return 0;
}

Main differences:

Feature C struct C++ struct
Member variables Supported Supported
Member functions Not supported Supported
Constructors Not supported Supported
Destructors Not supported Supported
Inheritance Not supported Supported
Access control No class-style access control Supports public, private, protected
Default member access Members can be accessed directly Default public

In C++, struct and class are basically the same in language capabilities; the main difference is default access permissions:

  • Default member access for struct is public.
  • Default member access for class is private.

2. References and Pointers

C supports pointers but does not support reference types in the C++ sense.

C:

#include <stdio.h>

void increment(int *value) {
    if (value != NULL) {
        (*value)++;
    }
}

int main(void) {
    int number = 10;

    increment(&number);

    printf("%d\n", number);

    return 0;
}

C++:

#include <iostream>

void increment(int& value) {
    value++;
}

int main() {
    int number = 10;

    increment(number);

    std::cout << number << '\n';

    return 0;
}

The main differences between the two are:

Comparison Pointer C++ Reference
Stores an address Yes Semantically, it is an alias for an object
Can be null Yes Must bind to a valid object under normal circumstances
Can be reseated Yes Cannot be rebound to another object
Usage Dereferenced via * Used directly
Supports pointer arithmetic Yes No
Supports multiple levels of indirection Yes No; a reference to a reference is not an ordinary reference type

Note that a C++ reference may be implemented via an address under the hood, but its language semantics are not equivalent to those of a pointer. References also cannot replace pointers in all scenarios.

5. Differences in Memory Management Mechanisms

Memory management is one of the important differences between C and C++.

1. C: malloc and free

C mainly manages memory through dynamic memory allocation functions in the standard library.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *arr = malloc(5 * sizeof(int));

    if (arr == NULL) {
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
    }

    free(arr);
    arr = NULL;

    return 0;
}

Core functions:

Function Purpose
malloc() Allocates a specified amount of memory and does not initialize its contents
calloc() Allocates memory and initializes all its bytes to zero
realloc() Adjusts the size of previously allocated memory
free() Frees dynamically allocated memory

C's dynamic memory management mainly relies on the programmer to explicitly control when memory is allocated and freed.

Common issues:

  • Memory leaks: allocated memory is not freed.
  • Double free: the same block of memory is freed multiple times.
  • Dangling pointers: a pointer points to an object or memory that is no longer valid.
  • Out-of-bounds access: accessing memory beyond the allocated range.

2. C++: new and delete

C++ provides the new and delete expressions for creating and destroying objects.

#include <iostream>

int main() {
    int* value = new int(100);

    std::cout << *value << '\n';

    delete value;
    value = nullptr;

    return 0;
}

Unlike C's malloc(), new not only allocates memory but also performs initialization according to the object type.

For class types, new calls the constructor, and delete calls the destructor.

Array allocation requires the corresponding array form:

int* arr = new int[5];

delete[] arr;

new[] must be paired with delete[] and must not be mixed with the non-array form.

3. C++ RAII Resource Management

C++'s more important memory management capability is not new and delete, but RAII (Resource Acquisition Is Initialization).

RAII binds resource acquisition to the object's lifetime:

  • Acquire resources when the object is constructed.
  • Release resources when the object is destroyed.
  • Use scope and destructors to perform cleanup automatically.

For example:

#include <iostream>
#include <memory>

int main() {
    auto value = std::make_unique<int>(100);

    std::cout << *value << '\n';

    return 0;
}

std::unique_ptr exclusively manages a dynamic object; when the smart pointer goes out of scope, it automatically releases the object it manages.

Common smart pointers:

Type Ownership Model Primary Use
std::unique_ptr Exclusive ownership An object has only one primary owner
std::shared_ptr Shared ownership Multiple objects share a resource's lifetime
std::weak_ptr Weak reference Observe a shared object while avoiding circular references

In real-world development, C++ generally favors standard containers, smart pointers, and RAII over heavy direct use of new and delete.

VI. Differences in Function Mechanisms

1. Function Overloading

C does not support defining multiple functions with the same name and different parameter lists.

int add_int(int a, int b) {
    return a + b;
}

double add_double(double a, double b) {
    return a + b;
}

C++ supports function overloading:

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

int main() {
    int a = add(1, 2);
    double b = add(1.5, 2.5);

    return 0;
}

The compiler selects the appropriate function based on the argument types and count at the call site, following the rules of overload resolution.

Note that C++ cannot overload a function solely on the basis of a different return type.

2. Default Arguments

C does not natively support default function arguments.

C++ supports default arguments:

#include <iostream>

void greet(const char* name, int age = 18) {
    std::cout << name << ", " << age << '\n';
}

int main() {
    greet("Tom");
    greet("Jerry", 25);

    return 0;
}

Default arguments are typically handled by the compiler at the call site based on the function declaration; they do not mean that argument inference is performed automatically at runtime.

3. Inline Functions

Both C and C++ support inline, but its semantics and usage rules are not entirely the same.

In C, the linkage rules for inline are rather peculiar, especially with respect to extern inline and the specific definitions in different C standards.

In C++, inline not only hints at inline optimization but also carries important semantics related to the ODR (One Definition Rule), allowing conforming inline function definitions to appear in multiple translation units.

Things to note:

  • inline does not guarantee that a function will actually be inlined.
  • The compiler may ignore the inline suggestion.
  • Even without writing inline, the compiler may still perform inline optimization automatically.

VII. Object-Oriented and Polymorphism Mechanisms

C does not natively support class inheritance or virtual functions, but similar designs can be simulated using structs, function pointers, and manual conventions.

1. Simulating Polymorphism in C with Function Pointers

#include <stdio.h>

typedef struct {
    void (*speak)(void);
} Animal;

void dog_speak(void) {
    printf("Woof\n");
}

void cat_speak(void) {
    printf("Meow\n");
}

int main(void) {
    Animal dog = {dog_speak};
    Animal cat = {cat_speak};

    dog.speak();
    cat.speak();

    return 0;
}

Here, different implementations are stored in function pointers, achieving an effect similar to dynamic dispatch.

However, this approach requires programmers to manually maintain object layouts, function pointers, and type conventions; it is not equivalent to a language's native inheritance and polymorphism system.

2. Runtime Polymorphism in C++ via Virtual Functions

#include <iostream>

class Animal {
public:
    virtual void speak() const {
        std::cout << "Animal\n";
    }

    virtual ~Animal() = default;
};

class Dog : public Animal {
public:
    void speak() const override {
        std::cout << "Woof\n";
    }
};

class Cat : public Animal {
public:
    void speak() const override {
        std::cout << "Meow\n";
    }
};

int main() {
    Dog dog;
    Cat cat;

    Animal* animals[] = {&dog, &cat};

    for (Animal* animal : animals) {
        animal->speak();
    }

    return 0;
}

Key mechanisms:

  • virtual declares a virtual function.
  • override explicitly indicates that a derived class overrides a base class virtual function.
  • A base class pointer can point to a derived class object.
  • When a virtual function is called through a base class pointer, dynamic dispatch is performed according to the actual object type.

Common C++ ABIs usually implement dynamic dispatch through a virtual function table (vtable) and a virtual pointer (vptr), but the C++ standard does not mandate this specific implementation.

In addition, if a class will destroy derived class objects through a base class pointer, the base class usually needs to have a virtual destructor; otherwise, undefined behavior may occur.

8. Differences in Generic Programming

1. C: Using void* and Macros to Implement Generic Operations

C does not have C++'s template mechanism; it usually uses void*, macros, or writes different functions for different types.

For example:

#include <stdio.h>

void print_value(const void* value, char type) {
    if (type == 'i') {
        printf("%d\n", *(const int*)value);
    } else if (type == 'd') {
        printf("%f\n", *(const double*)value);
    }
}

int main(void) {
    int a = 10;
    double b = 3.14;

    print_value(&a, 'i');
    print_value(&b, 'd');

    return 0;
}

This approach can handle data of different types, but it has some problems:

  • Type information must be passed additionally.
  • Type conversions must be handled by the programmer.
  • Incorrect types may lead to undefined behavior.
  • The compiler cannot perform complete compile-time checking for specific types as it can with templates.

2. C++: Using Templates to Implement Generics

C++ provides a template mechanism, allowing code to be written independently of specific types.

#include <iostream>

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(1, 2) << '\n';
    std::cout << add(1.5, 2.5) << '\n';

    return 0;
}

The compiler generates the corresponding instantiated code based on the template arguments.

Main advantages of templates:

  • Compile-time type checking.
  • Reduced code duplication.
  • Support for generic containers and algorithms.
  • Support for template specialization and compile-time computation.
  • Ability to build high-performance generic abstractions.

C++ templates are used not only for functions but also for classes, variables, and other template constructs.

9. Differences in Exception Handling Mechanisms

1. C: Handling Errors Through Return Values and Error Codes

C has no native try, catch, and throw exception handling syntax.

A common approach is to indicate the execution result through return values:

#include <stdio.h>

int divide(int a, int b, int* result) {
    if (b == 0 || result == NULL) {
        return -1;
    }

    *result = a / b;
    return 0;
}

int main(void) {
    int result;

    if (divide(10, 2, &result) != 0) {
        printf("Division failed\n");
        return 1;
    }

    printf("%d\n", result);

    return 0;
}

Characteristics of this approach:

  • The error handling path is explicit.
  • The caller needs to check the return value.
  • Error propagation usually needs to be handled layer by layer.
  • Resource cleanup needs to be explicitly organized by the developer.

C can also use mechanisms such as errno, setjmp(), and longjmp() to handle specific error scenarios, but they are not equivalent to the C++ exception mechanism.

2. C++: Support for Exception Mechanisms

```cpp #include #include double divide(double a, double b) { if (b == 0) { throw std::runtime_error("Division by zero"); } return a / b; } int main() { try { std::cout << divide(10, 2) << '\n'; std::cout << divide(10, 0) << '\n'; } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; } ```

Core syntax:

Keyword Purpose
try Defines a region of code that may throw exceptions
throw Throws an exception object
catch Catches and handles an exception

C++ exception handling usually involves stack unwinding.

When an exception leaves the current scope, objects with automatic storage duration that have already been fully constructed are destroyed according to the destructor rules. This is also why RAII can work together with exception safety.

Note that exceptions are not an error-handling approach every C++ project must adopt. Embedded, real-time, or certain performance-sensitive projects may disable exceptions and instead handle errors with error codes, std::expected, and similar approaches.

10. Differences in the Standard Libraries

Both C and C++ have standard libraries, but the level of abstraction and the scope of functionality they provide differ.

1. The C Standard Library

The C standard library provides basic, general-purpose functionality:

Header Main functionality
stdio.h Input and output
stdlib.h Memory allocation, program control, general utilities
string.h String and memory operations
math.h Mathematical operations
time.h Time handling
ctype.h Character classification and conversion
stdint.h Fixed-width integer types
stdbool.h Boolean type support

2. The C++ Standard Library

Beyond basic functionality, the C++ standard library provides a large number of high-level abstractions.