Useful information sharing: Correct use of const, static, extern

Useful information sharing: Correct use of const, static, extern

Preface

This article mainly introduces how to use the three keywords const, static, and extern in development. If you like my article, you can follow my Weibo: 吖了个郑, or you can come to Xiaoma Ge to learn about our iOS training courses. More content will be updated later. . .

1. The difference between const and macro (interview question):

Introduction to const: String constants that were commonly used before were generally extracted into macros, but Apple does not recommend that we extract macros and recommends that we use const constants.

Compile time: macros are precompiled (processed before compilation), and const is at the compilation stage.

Compilation check: Macros do not do any checking and will not report compilation errors, they are just replaced. Const will do compilation checking and will report compilation errors.

Advantages of macros: Macros can define some functions and methods, but const cannot.

Disadvantages of macros: Using a large number of macros can easily cause long compilation time and they need to be replaced every time.

Note: Many blogs say that using macros will consume a lot of memory. My verification does not generate a lot of memory. Macros define constants, which are placed in the constant area and only generate one copy of memory.

  1. // Common constants: extract macros  
  2. #define XMGAccount @ "account"  
  3.  
  4. #define XMGUserDefault [NSUserDefaults standardUserDefaults]
  5.  
  6. // String constant  
  7. static NSString * const account = @ "account" ;
  8.  
  9. - ( void )viewDidLoad {
  10. [ super viewDidLoad];
  11.  
  12. // Preferences storage  
  13. // Using macros  
  14. [XMGUserDefault setValue:@ "123" forKey:XMGAccount];
  15.  
  16. // Using const constants  
  17. [[NSUserDefaults standardUserDefaults] setValue:@ "123" forKey:account];
  18.  
  19. }

2. The role of const: limiting types

1.const is only used to modify the variable on the right (basic data variable p, pointer variable *p)

2. Variables modified by const are read-only.

Basic use of const

  1. - ( void )viewDidLoad {
  2. [ super viewDidLoad];
  3.  
  4. // Define variables  
  5. int a = 1 ;
  6.  
  7. // Allow modification of values  
  8. a = 20 ;
  9.  
  10. // Two usages of const  
  11. // const: modify the basic variable p  
  12. // These two ways of writing are the same, const only modifies the basic variable b on the right  
  13. const   int b = 20 ; // b: read-only variable  
  14. int   const b = 20 ; // b: read-only variable  
  15.  
  16. // Modification of value is not allowed  
  17. b = 1 ;
  18.  
  19. // const: modifies the pointer variable *p. The variable with * is the pointer variable.  
  20. // Define a pointer variable pointing to int type, pointing to the address of a  
  21. int *p = &a;
  22.  
  23. int c = 10 ;
  24.  
  25. p = &c;
  26.  
  27. // Allows modification of the address pointed to by p,  
  28. // Allow modification of the value of p accessing memory space  
  29. *p = 20 ;
  30.  
  31. // const modifies the memory space accessed by the pointer variable, modifying the right side *p1,  
  32. // Both methods are the same  
  33. const   int *p1; // *p1: constant p1: variable  
  34. int   const *p1; // *p1: constant p1: variable  
  35.  
  36. // const modified pointer variable p1  
  37. int * const p1; // *p1: variable p1: constant  
  38.  
  39.  
  40. // The first const modifies *p1 The second const modifies p1  
  41. // Both methods are the same  
  42. const   int * const p1; // *p1: constant p1: constant  
  43.  
  44. int   const * const p1; // *p1: constant p1: constant  
  45.  
  46. }

3. Usage scenarios in const development:

1. Requirement 1: Provide a method whose parameter is an address. The value can only be read through the address, but not modified through the address.

2. Requirement 2: Provide a method whose parameter is an address, and the address of the parameter cannot be modified.

@implementation ViewController

  1. //Putting const in front of * constrains the parameter, indicating that *a is read-only  
  2. // You can only modify address a, and you cannot modify the memory space accessed through a  
  3. - ( void )test:( const   int * )a
  4. {
  5. // *a = 20;  
  6. }
  7.  
  8. //Putting const after * constrains the parameter, indicating that a is read-only  
  9. // The address of a cannot be modified, only the value accessed by a can be modified  
  10. - ( void )test1:( int * const )a
  11. {
  12. int b;
  13. // Will report an error  
  14. a = &b;
  15.  
  16. *a = 2 ;
  17. }
  18.  
  19. - ( void )viewDidLoad {
  20. [ super viewDidLoad];
  21. // Do any additional setup after loading the view, typically from a nib.  
  22.  
  23. int a = 10 ;
  24.  
  25. // Requirement 1: Provide a method whose parameter is an address. The value can only be read through the address, and the value cannot be modified through the address.  
  26.  
  27. // At this time, you need to use const to constrain the method parameters to be read-only.  
  28. [self test:&a];
  29.  
  30. // Requirement 2: Provide a method whose parameter is an address, and the address of the parameter cannot be modified.  
  31. [self test1:&a];
  32. }
  33.  
  34.  
  35. @end  

4. Simple use of static and extern (to use something, first understand its function)

static effect:

Modify local variables:

1. Extend the life cycle of local variables so that they will be destroyed only when the program ends.

2. Local variables will only generate one copy of memory and will only be initialized once.

3. Change the scope of local variables.

Modifying global variables

1. Only accessible in this file, modifying the scope of global variables, the life cycle will not change

2. Avoid redefining global variables

Extern function:

It is only used to obtain the value of global variables (including global static variables) and cannot be used to define variables.

How extern works:

First, search for global variables in the current file. If not found, search other files.

  1. // Global variables: only one copy of memory, shared by all files, used in conjunction with extern.  
  2. int a = 20 ;
  3.  
  4. // static modifier global variable  
  5. static   int age = 20 ;
  6.  
  7. - ( void )test
  8. {
  9. // static modified local variables  
  10. static   int age = 0 ;
  11. age++;
  12. NSLog(@ "%d" ,age);
  13. }
  14.  
  15. - ( void )viewDidLoad {
  16. [ super viewDidLoad];
  17. // Do any additional setup after loading the view, typically from a nib.  
  18.  
  19.  
  20. [self test];
  21. [self test];
  22.  
  23. extern int age;
  24. NSLog(@ "%d" ,age);
  25. }
  26. I

5. Use static and const together

Static and const functions: declare a read-only static variable

Development usage scenario: string constants frequently used in a file can be combined with static and const

  1. // In development, static is often used to modify global variables, only changing the scope  
  2.  
  3. // Why do we need to change the scope of global variables to prevent repeated declaration of global variables?  
  4.  
  5. // Some global variables declared during development are not allowed to be modified by outsiders and can only be read.  
  6.  
  7. // For example, a basic data type does not want others to change it  
  8.  
  9. //Declare a static global read-only constant  
  10. static   const   int a = 20 ;
  11.  
  12. // The function of the combination of staic and const: declare a static global read-only constant  
  13.  
  14. // The common usage scenario of staic and const in iOS is to replace macros and define a frequently used string constant as a static global read-only variable.  
  15.  
  16. //During development, we often need to modify the key value, so we modify the key with const, which means that the key is read-only and cannot be modified.  
  17. static NSString * const key = @ "name" ;
  18.  
  19. // If const modifies *key1, it means *key1 is read-only, and key1 can still be changed.  

static NSString const *key1 = @"name";

6. Use extern and const together

Usage scenarios in development: The same string constant that is often used in multiple files can be combined with extern and const.

reason:

Combination of static and const: A static global variable needs to be defined in each file.

Combination of extern and const: only one global variable needs to be defined and multiple files can share it.

Formal writing of global constants: It is convenient to manage all global variables during development. Usually, a GlobeConst file is created to define global variables and manage them in a unified way. Otherwise, it will be difficult to find many project files.

  1. GlobeConst.h
  2.  
  3. /*******************************front page****************************/  
  4.  
  5. extern NSString * const nameKey = @ "name" ;
  6.  
  7. /*******************************front page****************************/  
  8.  
  9. GlobeConst.m
  10.  
  11. # import <Foundation/Foundation.h>
  12.  
  13. /*******************************front page****************************/  
  14.  
  15. NSString * const nameKey = @ "name" ;
  16.  
  17.  
  18. /*******************************front page****************************/  

<<:  Following Alibaba's reduction in recruitment, Baidu announced that it would stop recruiting from outside the company starting today. If you want to join, you need Robin's special approval.

>>:  Android slide close activity

Recommend

Microsoft is working on Android Launcher

[[142899]] Microsoft is currently developing a la...

App Store 5th Anniversary: ​​A Review of the Best Apps of the Year

In July 2008, Apple officially launched the App S...

Artifact recommendation! 10 niche, easy-to-use and high-end operation tools!

It is said that if the underwear is well chosen, ...

Will Windows 7 really not work with new CPUs in the future?

A piece of news about Windows 10 these days has ma...

Mathematics and Programming

Many people have written to me and asked me, what...

Analysis report on competitive products of Dewu and Shihuo

This is my first attempt at writing a competitive...

Happy, happy, how can I get you

Depression, a global public health problem, affec...

2019 Tik Tok and Kuaishou User Research Report!

Kuaishou and Douyin, as the two representative pl...