Preface:

We look at the source code, or interview often encountered some keywords, and due to the related articles on the Internet part of the point of view is wrong, I here summarized my previous notes and refer to the relevant books, standing on the shoulders of giants, integration of this article.

In a word, to promote, to interview, it is necessary to know these keywords. For each point, I try to explain it in terms of code.

extern

When the compiler encounters an extern template declaration, it does not generate instantiation code in this file. Declaring an extern indicates the developer’s commitment to having a non-extern definition of the instantiation elsewhere in the program. There may be multiple extern declarations for a given instantiated version, but there must be only one definition.

1. Declare variables in implementation files of other files (DWConst)

// dwconst. m // defines a const NSString *myExtern = @ that can be accessed by the entire program"abc";
@implementation DWConst

@end
Copy the code

2. Assign and print in the ViewController class (without importing dwconconst. H)

// ViewController.m
extern NSString *myExtern;
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"myExtern=%@", myExtern);
    NSLog(@"MyExtern address = % p", &myExtern);
    myExtern = @"hello";
    NSLog(@"myExtern=%@", myExtern);
    NSLog(@"Reassigned myExtern address =%p", &myExtern);
}
Copy the code

Print: myExtern= ABC myExtern address = 0x108aAF180 myExtern= Hello Reassigned myExtern address = 0x108aAF180

After definition, no matter how it is used, it only shares the same memory address (see print above), indicating that changing values in one place affects other places.

static

1. Modify global variables
  • Global variables are scoped only to the current file (limited scope)
2, modify local variables (the following three functions, in my opinion, are essentially the same)
  • Only one memory is guaranteed to open up
  • It will only be initialized once
  • The scope of the local variable is not changed, only the lifetime of the local variable is changed (the local variable is not destroyed until the end of the program).
- (void)viewDidLoad {
    NSLog(@"----------------- ViewDidLoad -----------------");
    [self testStatic]; } // The button creation code has been omitted - (void)btnClicked {NSLog(@"----------------- btnClicked -----------------");
    [self testStatic];
}

- (void)testStatic {
    NSInteger i = 0;
    i++;
    static NSInteger staticValue = 0;
    staticValue++;
    NSLog(@"Address of I =%p, address of staticValue =%p", &i, &staticValue);
}
Copy the code

Print: — — — — — — — — — — — — — — — — — ViewDidLoad — — — — — — — — — — — — — — — — — I address = 0 x7ffee2200948, StaticValue address = 0 x10d9ff1c8 — — — — — — — — — — — — — — — — — btnClicked — — — — — — — — — — — — — — — — — I address = 0 x7ffee2200fd8, = 0 x10d9ff1c8 staticValue address

The address for staticValue remains unchanged, proving that only one memory is guaranteed to be created.

NSLog(@” I =%p, staticValue =%p”, &i, &staticValue); Replace with NSLog(@” I = %ld, s.value = %ld”, (long) I, (long)staticValue);

Print: —————– ViewDidLoad —————– i = 1, s.value = 1 —————– btnClicked —————– i = 1, s.value = 2

Static value: +1; I: +1; static value: +1

const

As for const, I’ll give you an example:

const int *p = NULL; *p = 20; / / an errorCopy the code

Const *p can only be assigned once. If the value is assigned again, the error will be Read-only variable is not assignable

int a = 10; p = &a; // Normal through NSLog(@"*p=%d", *p);
    NSLog(@"p=%p", p);
Copy the code

Print: *p=10 p= 0x7ffeEC2a9a04

    int * const p1 = NULL;
    NSLog(@"p1=%p", p1); *p1 = 30; // The compiler passed, but an error was reportedCopy the code

See clear! P can still be modified, unlike *p. Because const modifies *p, not p

The difference between *p and p: *p is a stored value, while p is a pointer. In the above example, the p pointer stores the memory address of A, and *p is equal to 10.

Similarly, in the use of id types

    NSString * const city = @"CN";
    city = @"US"; / / an error,Copy the code

City decorated by const is read-only

Static and const

1, use,
static const CGFloat Height = 180;
static const CGFloat author = @"Dwyane";
Copy the code
2, and#defineThe contrast of
  • Common ground: Once defined, no modification is allowed
  • Difference:static constModify variable has only one copy of memory, check data type;#defineSimple text substitution, no checking of type, creating a memory for each use

Inline function

Before we get into inline functions, let’s take a look at how time-consuming calling functions can be

#include <stdio.h>
#include <time.h>

float addTime(long int a, float b)
{
    float result;
    result = a + b;
    return result;
}

int main(a)
{
    long int i;
    float result = 0;
    
    time_t start_time, stop_time;
    
    time(&start_time);
    printf("Start counting cycle times... \n");
    for(i = 1; i <= 1000000000; i++)
    {
        result += i;
    }
    time(&stop_time);
    printf("Total elapsed time :%ld\n",stop_time-start_time);
    printf("result = %f\n", result);
    result = 0;
    time(&start_time);
    printf("Start counting function call time... \n");
    for(i = 1; i <= 1000000000; i++)
    {
        result = addTime(i, result);   // Use function calls to consume time
    }
    printf("result = %f\n", result);
    time(&stop_time);
    printf("Total elapsed time :%ld\n",stop_time-start_time);
    
    return 0;
    }

Copy the code
// Print the result and start counting the cycle time... Total elapsed time :3 result = 18014398509481984.000000 Start counting function call time... Result = 18014398509481984.000000 Total elapsed time :6 Program ended withexit code: 0
Copy the code

The above code, one is the method of adding, one is the method of calling the function of adding, are doing the same thing (cumulative sum), get the same result, but calling the function of adding is far more time-consuming than the method of adding. This is sufficient to indicate that calling a function is very time-consuming, but many times we have to use a function, in order to maximize efficiency, inline function

1, use,
static inline int DWMax(int x, int y) {
    return (x > y)? x : y;
}
- (void)viewDidLoad {
      int i = DWMax(20, 30);
      NSLog(@"max = %d", i);
}
Copy the code

Advantages and disadvantages of ordinary functions

2. The purpose of introducing inline functions

For some functions whose body code is not very large, but which are called frequently, it is more important to solve the efficiency problem. Inline functions were introduced to solve this problem.

3. Abuse of inline functions

Misuse of inline will slow down your program. Inlining may increase or decrease the amount of object code, depending on the size of the inline function. Inlining very short access functions usually reduces the code size, but inlining a fairly large function increases the code size dramatically. Modern processors make better use of the instruction cache, and smaller code often executes faster.

Note: Inline functions are just requests we provide to the compiler, and the compiler does not necessarily call the function inline. In addition, if not requested, the compiler will optionally assemble inline functions automatically

Conclusion: A good rule of thumb is not to inline functions more than 10 lines. Be careful with destructors. Destructors are often longer than they appear because there are implicit member and base class destructors being called! Another useful rule of thumb: it is often not worth inlining functions that contain loops or switch statements (unless, in most cases, those loops or switch statements are never executed). –> Reference

Inline functions compare with #define

It is also recommended to see the difference between macros and ordinary functions

Inline functions differ from #define: 1. Macro calls do not perform type checking, even for normal arguments, while function calls do. C macros use text substitution, which can have unexpected consequences because of the need to recalculate parameters and order of operations. 3. Many constructs use macros or use different syntax to express things that are difficult to understand. Inline functions use the same language as normal functions and can be inlined or not inlined at will. Debugging information for inline code is often more useful than extended macro code.




The Static reference

Reference to inline functions

IOS OC inline function inline