Modern C++ and C Alternatives

Namespaces and C Name Prefixes

C++ namespaces create scoped names; C libraries commonly prefix public identifiers because C has one global function namespace.

What is Namespaces and C Name Prefixes?

C++ namespaces create scoped names; C libraries commonly prefix public identifiers because C has one global function namespace.

Prevent symbol collisions in larger programs.

Important points

  • Understand the C mechanism before comparing the C++ abstraction.
  • Use RAII and value semantics to express ownership.
  • Prefer type-safe compile-time abstractions over macros and casts.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

int math_square(int value) {
    return value * value;
}

int main(void) {
    printf("%d\n", math_square(7));
}
Expected output
49
C++
Run code →
main.cpp
#include <iostream>

namespace math {
    int square(int value) {
        return value * value;
    }
}

int main() {
    std::cout << math::square(7) << '\n';
}
Expected output
49

C and C++ comparison

A C prefix is a naming convention enforced by people. A C++ namespace is enforced by the compiler and supports aliases and qualified lookup.

C

C uses naming conventions, callbacks, macros, and explicit context structures.

C++

Language features provide scoped, type-safe, and often zero-overhead abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Write the C mechanism before the C++ abstraction.
  • Remove manual cleanup with RAII.
  • Check whether the abstraction adds allocations or virtual dispatch.