Skip to content

VS C VS C++

C非常简单,属于非常低级的语言,并没有太多的抽象、概念;而C++则有非常多的抽象、概念,是一门比较高级的语言。

What C++ enhance?

思路: C++在C上所增强的,主要方面:

OOP

C++支持OOP,因此很多概念就需要向OOP扩展,在C++\Language-reference\Basic-concept\index.md中对这个问题进行了深入分析。

Type system

参见 ./Type-system

Generic programming

主要是template-meta programming。

Library

C++的standard library提供的功能过多。

name space and scope

c++中可以显式定义name space,c中的name space是隐式的;

name space

c namespace

c++ namespace

scope

在c中,struct并不是一个scope;在c++中,struct是一个scope;

以下是取自Lookup and name spaces in C:

Unlike in C++, enumeration constants are not struct members, and their name space is the name space of ordinary identifiers, and since there is no struct scope in C, their scope is the scope in which the struct declaration appears:

struct tagged_union 
{
   enum {INT, FLOAT, STRING} type;
   int integer;
   float floating_point;
   char *string;
} tu;

tu.type = INT; // OK in C, error in C++
所以在c中enum就非常奇怪;

words

cc++的source code中的word的分类相同: - keyword - identifier

entity

C

C中并没有给出entity的定义。

C++

The entities of a C++ program are values, objects, references, structured bindings (since C++17), functions, enumerators, types, class members, templates, template specializations, namespaces, and parameter packs. Preprocessor macros are not C++ entities.

Entities are introduced by declarations, which associate them with names and define their properties. The declarations that define all properties required to use an entity are definitions. A program must contain only one definition of any non-inline function or variable that is odr-used.

SUMMARY

显然,两种语言对entity的定义不同,c中包含了macro,,而c++中则将其剔除了;entity是编译时概念,而不是preprocessor概念;

T::F

flexible array member中有这样的一段描述:

which is probably not something that you want to write on a daily base. A particularity in that expression is P99_SIZEOF(T, F[0]) which stands for the size of the element F[0] inside the struct type T. C doesn’t have the possibility as C++ to refer to a field in a type with something like T::F.

Something similar can be obtained in C99 with the magic formula sizeof((T){ 0 }.F[0]): define a compound literal (T){ 0 } of type T and take its field F. The sizeof operator actually ensures that this compound literal is never allocated, only the field F is taken for its type and size. This magic works in function scope (the compound literal would be of storage class auto) and in file scope (it would be static).

Assignment operators

In c:

The value category of the assignment operator is non-lvalue (so that expressions such as (a=b)=c are invalid).

In c++:

In C++, assignment operators are lvalue expressions, not so in C

Increment/decrement operators

https://en.cppreference.com/w/c/language/operator_incdec

Unlike C++ (and some implementations of C), the increment/decrement expressions are never themselves lvalues: &++a is invalid.

linkage规则的差异

参见Storage class specifiers#Notes