What's the meaning of static variables in an implementation of an interface?

后端 未结 4 1788
悲哀的现实
悲哀的现实 2020-12-04 09:37

I don\'t quite understand static variables when defined in the implementation of an interface. In methods I do understand how they differ from local variables, but not when

4条回答
  •  [愿得一人]
    2020-12-04 10:14

    Unfortunately, it has different effects depending on where you use it.

    Static Functions:
    By default, all functions have a global scope. The static specifier lets you limit the function’s scope to the current file.

    Static Local Variables:
    When you use the static modifier on a local variable, the function “remembers” its value across invocations. For example, the currentCount variable in the following snippet never gets reset, so instead of storing the count in a variable inside of main(), we can let countByTwo() do the recording for us.

    // main.m
    #import 
    
    int countByTwo() {
        static int currentCount = 0;
        currentCount += 2;
        return currentCount;
    }
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            NSLog(@"%d", countByTwo());    // 2
            NSLog(@"%d", countByTwo());    // 4
            NSLog(@"%d", countByTwo());    // 6
        }
        return 0;
    }
    

    This use of the static keyword does not affect the scope of local variables.
    Read more about the static keyword.

提交回复
热议问题