objective-c: Functions and static keyword

本文深入讲解了C语言中函数的概念及使用方法,包括定义、声明、实现等方面,并介绍了如何使用指针作为返回值或参数。此外,还探讨了静态函数的作用范围及静态局部变量的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值