Some Missing Knowledge Points of C Programming Language for C++ Programmer
As a programmer with C++ as the first programming language, I have been unfamiliar with some important features and idioms of C programming language. By reading "The C Programming Language", some missing knowledge points are sorted out as follows.
1. extern declaration
The keyword extern
is used to declare external
variables. And there are differences between declaration and
definition:
- definition: It means creating variables or allocating memory units.
- declaration: It just describes the nature of the variable, but does not allocate memory.
When the definition of an external variable appears before the
function that uses it, the extern
declaration can be
omitted; otherwise, there must be an extern
declaration
(for example: involving multiple source files).
Example:
1 |
|
Modifying an external variable or function with the
static
keyword can limit the scope of the object declared
later to the rest of the compiled file, and other files cannot access
the object.
The keyword static
can also be used to declare internal
variables: variables that can only be used within a function but always
occupy memory space.
2. macro
1 |
|
conditional include
example 1:
1 |
|
which is equal to:
1 |
|
example 2:
1 |
|
3. union
union
: Variables that hold objects of different types
and lengths at different times.
example:
1 |
|
union
is actually struct
, all its members
have an offset of 0 relative to the base address, this
struct
space should be large enough to accommodate the
widest member, and its alignment should be suitable for
members of all types in a union
.
4. bit-field
example:
1 |
|
Bit-field is not an array and has no address, the &
operator cannot be used on it.
5. File Operation
example:
1 |
|