• objective-c: Functions and static keyword


    Functions

    function is a concept for C programming language, objective-c is entirely relies on C.
    To define a function, you need provide four components: return value, function name, parameters and code block.
    like this:
    1
    2
    3
    int getRandomInteger(int minimum, int maximum) {
    return arc4random_uniform((maximum - minimum) + 1) + minimum;
    }

    the return value is a integer value, function name is getRandownInteger, there are two paramters: minimum and maximum, code block is enclosed by braces.

    Function also can use pointer reference as return value or paramaters, like this:
    1
    2
    3
    4
    5
    NSString *getRandomMake(NSArray *makes) {
        int maximum = (int)[makes count];
        int randomIndex = arc4random_uniform(maximum);
        return makes[randomIndex];
    }
    The declaration and implementation can be sepearted, the declaration tells the compiler that these is a function and the implementation do the real work.
    1
    2
    3
    4
    5
    6
    7
    8
    // Declaration
    NSString *getRandomMake(NSArray *);
    // Implementation
    NSString *getRandomMake(NSArray *makes) {
        int maximum = (int)[makes count];
        int randomIndex = arc4random_uniform(maximum);
        return makes[randomIndex];
    }
    If a method want call function , the function declaration should be defined before the method.
    static word
    static functions
    By default, all functions have a global scope, if you want limit the function’s scope to the current file, use ‘static’ keyword:
    1
    2
    3
    4
    5
    6
    // Static function declaration
    static int getRandomInteger(int, int);
    // Static function implementation
    static int getRandomInteger(int minimum, int maximum) {
        return arc4random_uniform((maximum - minimum) + 1) + minimum;
    }
    Note that static keyword should be use on both the function declaration and implementation.
    static local variable
    By defualt, the local variable in a function will be reset each time the function is called. If you use ‘static’ midifier on a local variable in a function , the variable value will be remembered.
    Note that the local variable’s scope do not changed, it still only accessible inside the function itself.
  • 相关阅读:
    【BZOJ2749】【HAOI2012】外星人[欧拉函数]
    【BZOJ3675】【APIO2014】序列分割 [斜率优化DP]
    【BZOJ2326】【HNOI2011】数学作业 [矩阵乘法][DP]
    【BZOJ1996】【HNOI2010】合唱队 [区间DP]
    【BZOJ1857】【SCOI2010】传送带 [三分]
    【BZOJ2338】【HNOI2011】数矩形 [计算几何]
    【BZOJ2330】【SCOI2011】糖果 [差分约束]
    【BZOJ1095】【ZJOI2007】捉迷藏 [动态点分治]
    【BZOJ4031】【HEOI2015】小Z的房间 [Matrix-Tree][行列式]
    【FJWC2017】交错和查询 [线段树]
  • 原文地址:https://www.cnblogs.com/zsw-1993/p/4879485.html
Copyright © 2020-2023  润新知