2017_11_06-const_in_cpp

来源:互联网 发布:百度推广怎么优化账户 编辑:程序博客网 时间:2024/06/05 20:22

const pointer

乔俊峰 Junfeng Qiao, 2017-11-06

最近看到了一篇很好的文章,终于搞清楚了const的用法。
现将重点摘抄如下:

  1. Every declaration in C and C++ has two
    principal parts: a sequence of zero or more
    declaration specifiers, and a sequence of
    one or more declarators, separated by
    commas.

    static unsigned long int *x[N];

    declaration specifiers: static unsigned long int

    declarator: *x[N];

    注意*是declarator

  2. The operators in a declarator group according
    to the same precedence as they do when
    they appear in an expression.

    所以[N]先与x结合,再与*结合,x is an “array of N elements of
    pointer to …” something

  3. Parentheses serve two roles in
    declarators: first, as the function call
    operator, and second, as grouping. As
    the function call operator, ()have the
    same precedence as []. As grouping,
    () have the highest precedence of all.

    *f(int) is a declarator
    specifying that f is a “function …
    returning a pointer … .” In contrast,
    (*f)(int) specifies that f is a “pointer
    to a function … .”

  4. A declarator may contain more
    than one identifier. The declarator
    *x[N] contains two identifiers, x and N.
    Only one of those identifiers is the
    one being declared, and it’s called the
    declarator-id. The other(s), if any,
    must have been declared previously.

    x is declarator-id

  5. Type specifiers contribute to the type of the
    declarator-id; other specifiers provide nontype
    information that applies directly to the
    declarator-id.

    static unsigned long int *x[N];
    unsigned long int is type specifiers.

  6. The keywords const and volatile are
    type specifiers.

  7. The order in which the declaration specifiers
    appear in a declaration doesn’t matter.

  8. The only declaration specifiers that can also
    appear in declarators are const and volatile.

  9. pointer declarations read from right-to-left.
    Always write const and volatile to the right.

    T const *p;
    T *const p;

  10. Recognizing the boundary between
    the last declaration specifier and the
    declarator is one of the keys to understanding
    declarations.

    Use const int *p;
    rather than const int* p;

文章地址:

http://www.dansaks.com/articles/1999-02%20const%20T%20vs%20T%20const.pdf

原创粉丝点击