Transition from C to C++ const

  • 2020-05-27 06:38:56
  • OfStack

1. Define constants

1.1 methods for defining constants in the C language

In this series, starting from scratch, we looked at how the C language defines constants. For those of you who haven't seen it, please refer to: C language from scratch (5) - constants & variable

I'm not going to go into the details of why we define constants, but I'm going to focus on what's wrong with this definition. A common interview question is: write down the results of the following code:

#include <stdio.h>

#define SUM 5 + 1;

void main()
  int a = 2 * SUM;
  printf("%d", a);

People often say 12, but it turns out to be 11. Try running 1 on your computer.

Why would it be wrong? Because the constants defined by #define are pseudo-constants, which do literal character substitutions at compile time. It's 2 times SUM which is what the compiler says it should be

int a = 2 * 5 + 1;

If you want to get 12, the definition should say:

#define SUM (5 + 1);

Such a classic mistake many people have made, although the truth is known to all, but always because of carelessness into this pit.

Thus, the introduction of C++ with the const constant completely solves this problem. Later, some compilers for the C language also began to support the use of const, which fully demonstrates its value.

1.2 const constants

In C++, we define constants in the following form:

const int MONTH = 12;
const int SUM = 5 + 1;

Strictly speaking, the const constant should be called a "constant variable", which defines a variable whose value will not be modified.

For the sake of code style 1, we still use all uppercase letters for the const constant.

The characteristics of

There are two major differences between const constant and ordinary constant:

You can't change the value
Can be used as a definition of array size
Such as:

const int MAX = 10;
int arr[MAX] = {0};
for (int i = 0; i < MAX; i++)
  // Do something

1.3 scope of action

The constants defined by const have a scope similar to static and can only be accessed by the current file. How do you write if you want to use it in other files?

// file1
const int MAX = 10;
// file 2
extern const int MAX;

While this is not recommended, it is recommended that you write the const definition in a header file, including this header file in the required files.

2. Pointer with const

The modification feature of the const is to modify the nearest part. It can be used in two ways.

2.1 pointer to the const variable

Having the pointer point to an const object prevents the pointer from modifying the value it points to.

int age = 30;
const int* ptr = &age;

This code defines a pointer ptr that points to data of type const int and is not modifiable.

  *ptr += 1;  //  An error 
  cin >> *ptr;  //  An error 

Both are illegal.

Note: you can still use the age variable.

2.2 const pointer

Declare the pointer itself as a constant to prevent the pointer position from changing

int a = 3;
int* const p = &a;

p++; //  error 

Note: only the const pointer can point to the const variable, for example:

const int a = 9;
const int* p = &a;   //  correct 
int* ptr = &a;     // error 

Special use:

const int* const p = &a;

This means that both the pointer variable and the address to which it is pointing are immutable

3. Functions and const

3.1 const parameters

If you want the parameter not to be modified inside the function, you can modify it with const, as follows:

void fun(const int a)
  a++; //  Illegal operation 

Since a is modified by const as a constant variable, an a++ operation on it will report an error.

The purpose of this method is to limit the change of parameters within the function, and more and more people like to do it like this:

void fun(int a)
  const int& b = a;
  b++; //  Illegal operation  

The effect is exactly the same.

3.2 const return value

If the return value of a function is a primitive data type, it makes no sense to modify it with const. Such as:

const int MONTH = 12;
const int SUM = 5 + 1;

The return value of the fun() function cannot be "left" modified, because no one would use it like this:

fun() = 2;
The compiler also filters this out first.

In general, const is only used to modify the return value to be a function of an object of a class. Such as:

const int MONTH = 12;
const int SUM = 5 + 1;

Can you understand the mystery? In conclusion 1, if the return value of const is an object of the class, then:

This return value cannot be left handed (it is assigned to the left of the equal sign or its member functions are called)
The alias for this return value must also be modified by const

4. Put 1 against 3

Knowing that 1 general parameter and return value are modified by const, we should be able to derive the case where const modifies pointer parameters and return value. Let's use a piece of code to look at the pitfalls.

const int MONTH = 12;
const int SUM = 5 + 1;

The various assignments in this program actually follow the principles described in part 2. In the process of parameter passing and value assignment, we need to pay attention to:

*p is not modifiable when pointer content is modified by const
When pointer content is modified by const, it cannot be assigned to a pointer whose content is not const
When both pointer variables and content are modified by const, you can only assign values to Pointers in the same situation
It's a mouthful to say, but when you think about it, it's similar to what you saw in part 2.

OK, that's all for today.

Related articles: