The difference between const and define in C language

Posted by skyer2000 on Mon, 21 Feb 2022 14:57:47 +0100

I const use

Const is the abbreviation of constant, which means "constant". The things modified by const are subject to mandatory protection, which can prevent accidental changes and improve the robustness of the program. So many C + + programming books suggest: "Use const whenever you need".

1.const modifier variable

#include <stdio.h>

int main() {
    const int a = 20 ;
    printf("a = %d\n",a);
    a = 200 ;
    printf("a = %d\n",a);
    return 0;
}

/*
 Output:
 
 Compilation Failed
 error: assignment of read-only variable 'a'
     6 |     a = 200 ;
       |     ~~^~~~~
 */

The value of a variable defined with const cannot be changed, that is, it cannot be re assigned, even if it is assigned the same value. And the const modified variable is given an initial value when it is defined, otherwise an error is reported:

error: uninitialized 'const ' [-fpermissive]

2.const modifier pointer

//The following two are equivalent, indicating that * p is immutable* p represents the content in the memory unit pointed to by the pointer variable p. at this time, this content is immutable;
const int *p
int const *p


//At this time, const modifies p, so the address of the memory unit stored in p is immutable, while the content of the memory unit is variable. That is, the direction of p is not variable, and the content of the memory unit pointed to by p is variable;
int * const p


//*If both p and p are modified, the address of the memory unit stored in p and the content in the memory unit are immutable;
const int * const p

3.const modifier in front of function name

When const is in front of the function name, it modifies the return value of the function; After the function name, it means that it is a C + + constant member function. This function cannot modify any member in the object. It can only read and write.

const char * GetString(void);
const int    GetInt(void);
const float  GetFloat(void);
const double GetDdouble(void);

If you add const modifier to the return value of a function in the "pointer transfer" mode, the content of the function return value (i.e. pointer) cannot be modified, and the return value can only be assigned to pointers of the same type with const modifier;

const char * GetString(void);

//The following statement will cause a compilation error:
//char *str = GetString();

//The correct usage is
const char  *str = GetString();

If the return value of the function adopts the "value transfer method", because the function will copy the return value to the external temporary storage unit, adding const decoration has no value.

int GetInt(void);

const int GetInt(void);

The above two functions exist independently, not the same function;

Modifier function name after const.4

When const is in front of the function name, it modifies the return value of the function; After the function name, it means yes C++ Constant member function, which cannot modify any member in the object, can only read and cannot write.

class People
{
 public:
    int talk(void);
    int eat(void) const; // const member function
 private:
    int m_age;
   
};
int People::eat(void) const
{
    ++m_age; // Compilation error, attempting to modify data member m_num
    talk();  // Compilation error, attempt to call non const function
    return    m_age;
}
  • Const objects can only access const member functions, while non const objects can access any member functions, including const member functions;
  • The members of const objects cannot be modified, but the objects maintained by const objects through pointers can be modified;
  • Const member function cannot modify the data of an object, regardless of whether the object has const property or not When compiling, it checks whether to modify the member data;
  • However, the data member with mutable modifier can be modified by any means in any case. Naturally, the const member function can modify it at this time;

5.const modifier function parameters

If the function parameter adopts "pointer passing", adding const decoration can prevent accidental change of the pointer and play a protective role.

void StringCopy (char*strDestination, const char *strSource);

Where strSource is the input parameter and strDestination is the output parameter. After adding const to strSource, if the statement in the function body tries to change the contents of strSource, the compiler will point out the error.

If the input parameter adopts "value transfer", since the function will automatically generate temporary variables to copy the parameter, the input parameter does not need to be protected, so do not add const modification.

For example, do not write the function void Func1(int x) as void Func1(const int x).

If a parameter is used as an output parameter, no matter what data type it is, or whether it adopts "pointer passing" or "reference passing", it cannot be modified with const, otherwise the parameter will lose its output function (because its value cannot be changed after const modification).

If the parameter is used as the input parameter, it can prevent the data from being changed, play a protective role and increase the robustness of the program;

II define use

1.define constant

In C language, an identifier can be defined with #define to represent a constant. The general form of defining an identifier with #define is:

#Define identifier constant / / note that there is no semicolon at the end of define
//For example:
#define MAX_VALUE 100 / / defines the integer variable Max_ The value value is 100
#define USER_NAME "huge" / / define the string variable user_ The name value is "huge"
#define PI 3.1415926 / / define the floating-point variable pI value as 3.1415926

All instructions beginning with # are preprocessing instructions, and preprocessing is also called precompiling. Precompiling is not compilation, but pre compilation processing. This operation is automatically completed by the system before formal compilation.

2.define function

//Define constants
#define MAX_VALUE 100 / / defines the integer variable Max_ The value value is 100
#define USER_NAME "huge" / / define the string variable user_ The name value is "huge"
#define PI 3.1415926 / / define the floating-point variable pI value as 3.1415926

//Define function
#define MAX(a,b) (a>b)? a: B / / take the maximum of two numbers
#define MIN(a,b) (a<b)? a: B / / take the minimum of two numbers

3.define multiline function

//Define constants
#define MAX_VALUE 100 / / defines the integer variable Max_ The value value is 100
#define USER_NAME "huge" / / define the string variable user_ The name value is "huge"
#define PI 3.1415926 / / define the floating-point variable pI value as 3.1415926

//Define simple functions
#define MAX(a,b) (a>b)? a: B / / take the maximum of two numbers
#define MIN(a,b) (a<b)? a: B / / take the minimum of two numbers

//Define complex multiline functions
#define   MACRO(arg1,   arg2)   do   {   \ 
   \ 
stmt1;   \ 
stmt2;   \ 
   \ 
}   while(0)  
  
//The key is to add a "\" at each line break

use define defines a multi line complex function , the key is to add a \;

4.define to prevent repeated inclusion of header files

Resolve the repeated inclusion of header files by #ifndef#define

#ifndef __XXX_H__
#define __XXX_H__

int a=1;

#endif

The pseudo code above is as follows:

If(No macro defined__XXX_H__)
{
    Then define the macro directly__XXX_H__
    Define variables a And assigned a value of 1
}
End program
  • If it is included for the first time, because there is no macro defined__ XXX_H__, So I did two things, defining macros__ XXX_H__, Then define int a = 1;
  • If it is included for the second time, because the macro has been defined__ XXX_H__, So do nothing;
  • If it is included for the nth time, because the macro has been defined__ XXX_H__, So do nothing;
  • In the whole process, no matter how many times the header file is included, the variable a is defined only once, and there will be no problem of repeated definition!

III Difference between const and define

1. In terms of the stage at work

#define works in the preprocessing stage of compilation, while const works during compilation and running.

2. In terms of how it works

#define is just a simple string replacement without type checking. const has a corresponding data type and needs to be judged, which can avoid some low-level errors.

3. In terms of storage mode

#define is only used for expansion. It can be replaced as many times as it is used. There are several backups of its macro constants in memory; The read-only variable defined by const has only one backup during the operation of the program.

4. In terms of the convenience of code debugging

const constant can be debugged, but define cannot, because it has been replaced in the precompile stage.

5. In terms of efficiency

The compiler usually does not allocate storage space for ordinary const constants, but saves them in the symbol table, which makes it a constant during compilation. Without the operation of storing and reading memory, it is also very efficient

IV const advantages

  • 1.const constants have data types, while macro constants have no data types. The compiler can perform type safety checks on the former. For the latter, only character replacement is performed without type safety check, and unexpected errors may occur in character replacement.
  • 2. Some integrated debugging tools can debug const constants, but cannot debug macro constants.
  • 3.const can save space, avoid unnecessary memory allocation and improve efficiency

This is the programming cabin of empty string. Pay attention to me. More small knowledge of C language will be released later. Our learning group [8815777770] hopes you can come in and communicate with more people to learn programming and make progress together~

Topics: C C++ visualstudio