zoukankan      html  css  js  c++  java
  • Just like normal variables,

    Just like normal variables, pointers can be declared constant. There are two different ways that pointers and const can be intermixed, and they are very easy to mix up.

    To declare a const pointer, use the const keyword between the asterisk and the pointer name:

    1
    2
    int nValue = 5;
    int *const pnPtr = &nValue;

    Just like a normal const variable, a const pointer must be initialized to a value upon declaration, and its value can not be changed. This means a const pointer will always point to the same value. In the above case, pnPtr will always point to the address of nValue. However, because the value being pointed to is still non-const, it is possible to change the value being pointed to via dereferencing the pointer:

    1
    *pnPtr = 6; // allowed, since pnPtr points to a non-const int

    It is also possible to declare a pointer to a constant variable by using the const before the data type.

    1
    2
    int nValue = 5;
    const int *pnPtr = &nValue;

    Note that the pointer to a constant variable does not actually have to point to a constant variable! Instead, think of it this way: a pointer to a constant variable treats the variable as constant when it is accessed through the pointer.

    Thus, the following is okay:

    1
    nValue = 6; // nValue is non-const

    But the following is not:

    1
    *pnPtr = 6; // pnPtr treats its value as const

    Because a pointer to a const value is a non-const pointer, the pointer can be redirected to point at other values:

    1
    2
    3
    4
    5
    int nValue = 5;
    int nValue2 = 6;
     
    const int *pnPtr = &nValue;
    pnPtr = &nValue2; // okay

    Confused?

    To summarize:

    • A non-const pointer can be redirected to point to other addresses.
    • A const pointer always points to the same address, and this address can not be changed.
    • A pointer to a non-const value can change the value it is pointing to.
    • A pointer to a const value treats the value as const (even if it is not), and thus can not change the value it is pointing to.

    Finally, it is possible to declare a const pointer to a const value:

    1
    2
    const int nValue;
    const int *const pnPtr = &nValue;

    A const pointer to a const value can not be redirected to point to another address, nor can the value it is pointing to be changed.

    Const pointers are primarily used for passing variables to functions. We will discuss this further in the section on functions.

    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    泛在电力物联网建设路线
    如何建设泛在电力物联网?
    泛在电力物联网到底该怎么建?
    泛在电力物联网(能源互联网+物联网)浅析
    泛在电力物联网分析—架构形式
    泛在电力物联网:两个业务 两种发展逻辑
    国网“泛在电力物联网”的战略与逻辑
    MVC中使用Hangfire按秒执行任务
    hangfire 实现已完成的job设置过期,防止数据无限增长
    解决ASP.NET Core部署到IIS,更新项目"另一个程序正在使用此文件,进程无法访问"
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4875601.html
Copyright © 2011-2022 走看看