Daily C Language Knowledge Point: The const Type Qualifier

A. Using const when declaring variables

const int nochange;

/* This restricts the value of the variable nochange from being modified */

const int nochange = 10;

/* This statement is correct */

const int nochange;

nochange = 10;

/* The compiler will report an error because it cannot be assigned a value after declaration */

B. Using const in pointer and parameter declarations

const float * pf;

/* pf points to a const value of type float, which cannot be changed. The value of pf itself can change, allowing the pointer to point to other const values */

float * const pf;

/* pf is a const pointer, meaning the value of pf itself cannot change. However, the value pointed to by pf can be changed */

const float * const pf;

/* pf cannot point elsewhere, and the value it points to cannot be changed */

float const * pf;

/* This is equivalent to const float * pf; */

Summary of rules:

When const is placed on the left side of *, it restricts the data pointed to by the pointer from being changed; when const is placed on the right side of *, it restricts the pointer itself from being changed.

Leave a Comment