Skip to content

Functions in C

C Programming Lesson 5 2:02 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
A C function tells you everything about itself in its first line. C 的函数在第一行就把自己的一切都说清楚了。
It starts with the return type — what comes back — and that is required; you cannot leave it out, and if the function gives nothing back you write void. 它以返回类型开头——也就是交还回来的东西——而且这是必须的;你不能省略, 如果这个函数什么也不返回,就写 void。
Then the name. 然后是名字。
Then, in the brackets, the parameters, and each one carries its own type. 再是括号里的形参,每一个都带着自己的类型。
Read that line and you know how to call it without reading the body. 读完这一行,你不用看函数体就知道该怎么调用它。
Now the behaviour that surprises people, and it matters more in C than anywhere else. 现在说那个会让人意外的行为,而它在 C 里比在别的地方更重要。
When you call a function, C hands it a copy of your value. 当你调用一个函数时,C 交给它的是你那个值的一份副本。
So inside, n is a separate box that happens to start with the same contents. 所以在函数里面,n 是另一个盒子,只是一开始装着相同的内容。
Adding one to it changes that copy and nothing else — back in main, x is still five. 给它加 1,改的是那份副本,别的什么都没变——回到 main 里,x 还是 5。
This is not a limitation to work around; it is the reason pointers exist, and lesson eight is about exactly that. 这不是一个需要绕开的限制;它正是指针存在的原因,而第 8 课讲的就是这个。
Now the lesson's first task, and it is really a lesson in building. 现在做课程里的第一道题,而它其实是一堂关于“搭建”的课。
Write max2, which returns the larger of two numbers — one line, using the question mark form or an if, whichever reads better to you. 先写 max2,返回两个数中较大的那个——一行就够, 用问号形式或者 if 都行,看你觉得哪个读起来更顺。
Then, for the largest of three, do not write a new comparison at all: call max2 on the first two, and call it again on that answer and the third. 然后要求三个数里最大的,就完全不用再写新的比较了: 先对前两个调用 max2,再拿这个结果和第三个数调用一次。
The function that already does it does it again. 已经会做这件事的函数,再做一次就好。
Four things to take with you. 带走四点。
One: the return type comes first and it is required — void when nothing comes back. 第一:返回类型写在最前面,而且必须写——什么都不返回就写 void。
Two: every parameter carries its own type. 第二:每个形参都带着自己的类型。
Three: arguments are copied, so changes inside are lost outside. 第三:实参是被复制进去的,所以函数内部的修改在外面看不到。
Four: build big functions out of small ones you have already tested. 第四:用已经测试过的小函数,搭出大的函数。
Now do the three tasks; the last one clamps a value between two limits. 现在去做那三道题;最后一题是把一个值限制在两个界限之间。

Log in or create account

IGCSE, A-Level & AP