Const modifier and pointer

Source: Internet
Author: User

There are three combinations of const and pointer: pointer to constant, constant pointer, and constant pointer to constant.

 

1. pointer to a constant

Definition: const data type * pointer variable name

Meaning: A pointer variable pointing to a constant.

Note: This pointer can be changed to another constant, but the constant pointed to by this pointer cannot be changed.

Example:

Const char * name = "Chen"; // declare the pointer name pointing to a constant

Name [3] = 'a'; // error. The value of the variable pointed to by the pointer cannot be changed.

Name = "Zhang"; // valid. The value of the pointer can be changed.

 

2. Constant pointer

Definition: Data Type * const pointer variable name = initialization value

Meaning: an unchangeable pointer variable pointing to a variable.

Note: initialization is required when defining regular pointers;

The value of this pointer cannot be changed, but the value of the variable pointed to by this pointer can be changed.

Example:

Char * const name = "Chen"; // declare the constant pointer name

Name [3] = 'a'; // valid. The variable value pointed to by the pointer can be changed.

Name = "Zhang"; // error. The pointer value cannot be changed.

 

3. Constant pointer to a constant

Definition: const data type * const pointer variable name = initialization value

Meaning: a constant pointer variable pointing to a constant.

Note: The pointer must be initialized during definition;

The value of this pointer and the value of the constant it points to cannot be changed.

Example:

Const char * const name = "Chen"; // declare a constant pointer to a constant

Name [3] = 'a'; // error. The variable value pointed to by the pointer cannot be changed.

Name = "Zhang"; // error. The pointer value cannot be changed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.