Explain the const keyword in C++ and how it differs from const in C

  • 2020-05-10 18:30:46
  • OfStack

The const object defaults to a local variable for the file, unlike other variables, which are defined when the const variable is global scoped, unless otherwise specified. This variable exists only in that file and cannot be accessed from other files. Specify extern (also in c) that must be displayed if the const variable is accessible from another file
 
When you only use the const constant in the file that defines it, c++ does not allocate space for your const constant -- this is one of the optimizations of c++. There is no need to waste memory space to store a constant. const int c = 0; This is equal to #define c 0;  
 
When used outside of the current file, c++ allocates space to your const (it has to be). Because if space is not allocated, then there is no information about this constant in obj at all. The constant cannot be found when connecting. Also if you take the address of a constant in your application, force c++ to allocate space to your constant.
 
C + + compiler under normal circumstances do not allocate space for constants, but its value in the symbol table. But when using extern modified constant, you must immediately for this constant allocation (a similar situation and take the address of the constants, etc.). So must allocate space, only because extern said "the use of external links", this indicates that there will be other compilation unit will use the method of addressing to refer to it, so it must have its own address right now.
 
So if you want to use the const variable of another file in the current file, this variable must be defined as :(m.cpp) extern const int aaa = 9999; For use :(main.cpp) extern const int aaa; In c it is no longer necessary to define extern, because space is always allocated for the const variable.

The form parameter overload of const:


#include <iostream>
 
using namespace std;
 
void f(int& a)
{
    cout << "void f(int& a)" << endl;
}
 
void f(const int& a)
{
    cout << "void f(const int& a)" << endl;
}
 
int main()
{
    int a = 6;
    int &b = a;
    const int c = 8;
 
    f(a);
    f(b);
    f(c);
    f(3);
 
    return 0;
}

 
Operation results:


void f(int& a)
void f(int& a)
void f(const int& a)
void f(const int& a)

The difference between C and const in C++

1. const in C++ is normally treated as a constant at compile time. The compiler does not allocate space for const, but only saves the period value in the name table at compile time and converts it into the code when appropriate.


#include <iostream>
using namespace std;
int main()
{
 const int a = 1;
 const int b = 2;
 int array[ a + b ] = {0};
 for (int i = 0; i < sizeof array / sizeof *array; i++)
 {
    cout << array[i] << endl;
 }
}

It can be compiled and run normally, but if you modify it slightly and put it in the C compiler, you will get an error:


#include <stdio.h>
int main()
{
 int i;
 const int a = 1;
 const int b = 2;
 int array[ a + b ] = {0};
 for (i = 0; i < sizeof array / sizeof *array; i++)
 {
    printf("%d",array[i]);
 }
}

Error message:


c:/test1/te.c(8): error C2057:  A constant expression should be entered 
c:/test1/te.c(8): error C2466:  You can't assign a constant of size zero  0  An array of 

The reasons for this are:
(1) in C,const is a common variable that cannot be changed, and since it is a variable, it takes up storage space, so the compiler does not know the compile-time value.
(2) in C:


const int size;

This statement is correct because it is treated by the C compiler as a declaration to allocate storage elsewhere, but it is not correct to write this in C++. const in C++ defaults to an internal connection, and you must use the extern keyword if you want to achieve this in C++.

2. In C++,const USES internal connections by default, while in C, external connections are used.
Inner join: the compiler creates storage space only for the files being compiled, other files can use the same token
          or global variable.C/C++ middle inner join is specified using the static keyword.
External connection: all compiled files create a single piece of storage space. Once the space is created, the connector must resolve the reference to this piece of storage space. Global variables and functions use external connections.


header.h
const int test = 1;
test1.cpp
#include <iostream>
#include "header.h"
using namespace std;
int main()
{
 cout << "in test1 :" << test << endl;
}
test2.cpp
#include <iostream>
#include "header.h"
using namespace std;
void print()
{
 cout << "in test2:" << test << endl;  
}

The above code compiles the connection without any problems, but if you change header.h to:


extern const int test = 1;

When connecting, the following error message will appear:


test2 error LNK2005: "int const test" (?test@@3HB)  Has been in  test1.obj  Defined in the 

Because the extern keyword tells the C++ compiler that test will be referenced elsewhere, the C++ compiler creates a storage space for test instead of simply storing it in the name table, so when two files contain both header.h, a name conflict occurs.
This is similar to the meaning of const in C:


header.h
const int test = 1;
test1.c
#include <stdio.h>
#include "header.h"
int main()
{
 printf("in test1:%d/n",test);
}
test2.c
#include <stdio.h>
#include "header.h"
void print()
{
 printf("in test2:%d/n",test);  
}


Error message:


void f(int& a)
void f(int& a)
void f(const int& a)
void f(const int& a)
0

In C++, whether or not space is allocated for const depends on the specific situation.
If you add the keyword extern or take the address of the const variable, the compiler will allocate storage space for const.
define is no longer used when defining constants in C++, because define does simple macro substitution and does not provide type checking


Related articles: