directory
- A. Use const
- 1. Const decorates a variable
- 2. Const decorates the pointer
- 3. Const precedes the function name
- 4. Const follows the function name
- 5. Const decorates the function argument
- 2. Define use
- 1. Define a constant
- 2. Define the function
- 3. Define multi-line functions
- 4. Define prevents repeated inclusion of header files
- 3. Const and define
- 1. In terms of the stage of action
- 2. In terms of how it works
- 3. In terms of storage mode
- 4. From the convenience of code debugging
- 5. In terms of efficiency
- 4. Advantages of const
- Five. Guess you like it
C/C++ learning Directory >> C language basics
A. Use const
Const is short for constant, “constant”. Anything decorated with const is forcefully protected against unexpected changes and improves the robustness of the program. So many C++ programming books advise: “Use const whenever you need.”
1. Const decorates a variable
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / / @ Author: programming ape said // @blog (personal Blog address): www.codersrc.com // @file :C language const and define difference // @time :2021/07/04 08:00 // @motto: Small steps without a thousand li, not small streams without rivers and oceans, the wonderful program life needs to be accumulated unrelentingly! /******************************************************************************************/ #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: the assignment of the read - only variable 'a' 6 | a = 200; | ^ ~ ~ ~ ~ ~ ~ * /Copy the code
The value of a variable defined by const is not allowed to change, that is, it is not allowed to be reassigned, even to the same value. Const const const const const const const const const const
error: uninitialized 'const ' [-fpermissive]
Copy the code
Const decorates a variable;
2. Const decorates the pointer
// *p is immutable. *p represents the contents of the memory unit pointed to by the pointer variable P, which is immutable. Const int *p int const *p // The address of the memory unit in p is immutable, but the contents of the memory unit are mutable. That is, the pointing of P is immutable, and the contents of the memory unit pointed to by P are variable. Int * const p //*p and p are both decorated, so that the address of the memory unit stored in p and the contents of the memory unit are immutable; const int * const pCopy the code
Const decorates a pointer;
3. Const precedes the function name
Const before the function name modifies the return value of the function; The C++ constant member function after the function name cannot modify any member of the object. This function can only perform reads, but not writes.
const char * GetString(void);
const int GetInt(void);
const float GetFloat(void);
const double GetDdouble(void);
Copy the code
If given”Pointer passedConst const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const const
const char * GetString(void); //char * STR = GetString(); // Const char * STR = GetString();Copy the code
If the function returns the value”Value transfer mode”, since the function copies the return value to an external temporary storage location, the const modifier has no value.
int GetInt(void);
const int GetInt(void);
Copy the code
The above two functions are independent, not the same function;
4. Const follows the function name
Const before the function name modifies the return value of the function; The C++ constant member function after the function name cannot modify any member of the object. This function can only perform reads, but not writes.
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / / @ Author: programming ape said // @blog (personal Blog address): www.codersrc.com // @file :C language const and define difference // @time :2021/07/04 08:00 // @motto: Small steps without a thousand li, not small streams without rivers and oceans, the wonderful program life needs to be accumulated unrelentingly! /******************************************************************************************/ class People { public: int talk(void); int eat(void) const; // const member function private: int m_age; }; int People::eat(void) const { ++m_age; M_num talk(); // compile error, attempt to call nonconst function return m_age; }Copy the code
- Const objects can access only const member functions. Nonconst objects can access any member function, including const member functions.
- Members of const objects are non-modifiable, whereas objects maintained by Pointers to const objects are modifiable.
- A const member function may not modify the data of an object, whether or not the object is const. At compile time, it checks whether the member data is modified.
- Whereas data members with the mutable modifier can be modified by any means in any case, const member functions can be modified accordingly.
5. Const decorates the function argument
If the function argument is “pointer passed,” the const modifier protects the pointer from accidental changes.
void StringCopy (char*strDestination, const char *strSource);
Copy the code
StrSource is the input parameter and strDestination is the output parameter. By adding const to strSource, the compiler will point out the error if a statement inside the function tries to alter the strSource’s contents.
If the input parameter is passed by value, it should not be const because the function automatically generates a temporary variable to copy the parameter.
For example, do not write void Func1(int x) as void Func1(const int x).
If a parameter is an output parameter, regardless of its data type or whether it is passed by pointer or by reference, it cannot be decorated with const. Otherwise, the parameter will lose its output function.
If the parameters as input parameters, can prevent data from being changed, play a protective role, increase the robustness of the program;
2. Define use
1. Define a constant
In C, you can use #define to define an identifier to represent a constant. The general form of the identifier defined with #define is:
#define identifier constant // Note that there is no semicolon at the end of define // for example: #define MAX_VALUE 100 #define USER_NAME "huge" #define PI 3.1415926 // Define the floating point variable PI as 3.1415926Copy the code
In the#
Preprocessing instructions, also known as precompilation, are used at the beginning. Precompilation is not compilation, but processing before compilation. This is done automatically by the system before formal compilation.
2. Define the function
// define constant #define MAX_VALUE 100 // define integer variable MAX_VALUE 100 #define USER_NAME "huge" // define string variable USER_NAME value "huge" #define PI #define MAX(a,b) (a>b)? #define MIN(a,b) (a<b)? A :b // Take the minimum of both numbersCopy the code
3. Define multi-line functions
// define constant #define MAX_VALUE 100 // define integer variable MAX_VALUE 100 #define USER_NAME "huge" // define string variable USER_NAME value "huge" #define PI #define MAX(a,b) (a>b)? #define MIN(a,b) (a<b)? #define MACRO(arg1, arg2) do {\ \ stmt1; \ stmt2; \ \} while(0) // The key is to add a "\ "to each newline.Copy the code
use
define
Define a complex function with multiple linesThe key is to add one at every newline\
;
4. Define prevents repeated inclusion of header files
#ifndef / #define to resolve repeated header inclusion
#ifndef __XXX_H__
#define __XXX_H__
int a=1;
#endif
Copy the code
The pseudocode above is as follows:
If (no macro __XXX_H__ is defined) {then the macro __XXX_H__ defines the variable a and assigns 1} to end the programCopy the code
- If the macro __XXX_H** was not defined for the first time, we did two things: define the macro __XXX_H**, and then define int a = 1;
- If the second include does nothing because the macro __XXX_H__ has been defined;
- If the NTH inclusion does nothing because the macro __XXX_H__ has been defined;
- The whole process, no matter how many times the header file is included, the variable A is defined only once, and there is no double inclusion of double definitions!
3. Const and define
1. In terms of the stage of action
#define is used during compilation preprocessing, while const is used at compile/run time.
2. In terms of how it works
#define is just a simple string substitution, no type checking. Const, on the other hand, has a corresponding datatype and is evaluated to avoid some low-level errors.
3. In terms of storage mode
#define is just expanded and replaced as many times as it is used. The macro constants it defines are backed up in memory. A read-only variable defined by const has only one copy during program execution.
4. From the convenience of code debugging
Const constants can be debugged. Define cannot be debugged because it is replaced during precompilation.
5. In terms of efficiency
Compilers usually do not allocate storage for ordinary const constants. Instead, they are stored in a symbol table. This makes them a compile-time constant and makes them efficient without storing and reading memory
4. Advantages of const
- 1. Const constants have data types, while macro constants have no data types. The compiler can perform type safety checks on the former. The latter, on the other hand, only performs character substitution, has no type safety check, and may produce unexpected errors during character substitution.
- 2. Some integrated debugging tools can debug const constants, but not macro constants.
- 3. Const can save space, avoid unnecessary memory allocation, improve efficiency
Five. Guess you like it
- C array subscript out of bounds and memory overflow difference
- C language pointer declaration and definition
- P ++ / p –
- The C languagep++/§ + + / _ (p++) / _p + +
- C language uses Pointers to iterate over groups of numbers
- C language pointer and array difference
- C language pointer array and array pointer difference
- C NULL pointer
- C void Pointers
- C language field pointer
- C function value passing and address passing
- Default parameter of C language function
- C language function variable parameter
- C function pointer
- C language pointer function
- C language callback function callback
- C typedef
- C defines constants
- C define prevents repeated inclusion of header files
- Pragma once
- C language #include <> is different from #include
- C const decorates a variable
- C const decorates Pointers
- C const modifier functions
- C const decorates function arguments
- C const is different from define
C C const and define
This article is published by the blog – Ape Say Programming Ape Say programming!