函数参数以值传递
Coddy 面向 Luau 开发者的 C 课程的第 17 课,共 48 课。
Luau 会按值传递每个参数:数字、布尔值或字符串会被复制;表参数会复制引用,因此函数可以更改调用方的表,但永远不能重新绑定调用方的变量。C 参数也会接收其值的副本。更改 int 参数无法更改调用方的变量。指针参数也会被复制,但它可以指向由调用方拥有、且函数可能会修改的存储空间。
Luau
local function change(n)
n = 9
end
local x = 2
change(x)
print(x)C17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static void change(int n){n=9;(void)n;}
int main(void) {
int x=2;change(x);printf("%d\n",x);
return 0;
}
移植规则
要区分更改复制得到的参数和通过指针写入。
挑战
简单输入是整数 n。返回 n 的两倍,同时保持调用方的副本不变。驱动程序会输出 original:doubled。
编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,因为它会直接调用该函数。不要添加另一个 main。除非任务明确检查范围,否则所有数值任务测试数据都足够小,不会溢出。只输出指定内容;如有展示,驱动程序会负责解析输入和输出。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n;if(scanf("%d",&n)!=1)return 1;int result=doubled(n);printf("%d:%d\n",n,result);return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 C中的所有课
自己练习: C 在线编译器