[英]Why does this code work? The input for the function is "string s" but the actual input we are giving is "int name". C language
SUMMARY OF THE CODE: This code is supposed to take a string input from the user and output how many characters there are.代码摘要:此代码应该从用户那里输入一个字符串,output 有多少个字符。 (Not using strlen intentionally)
(不故意使用 strlen)
NOTE: So this is a code in CS50 course by Harvard and get_string is function implemented by the teachers to circumvent the scanf function.注意:所以这是哈佛 CS50 课程中的代码,get_string 是教师实施的 function 以规避 scanf function。
MY DOUBT: See how that user-defined function int string_length (string s), got "string s" as input and an int as a return value.我的疑问:看看用户定义的 function int string_length (string s),如何得到“string s”作为输入和一个 int 作为返回值。
But later in the main() part of the code the variable we store the string that the user inputs into is "name" but "name" is never used again in the implementation of string_length and instead "s" is used.但是稍后在代码的 main() 部分中,我们存储用户输入的字符串的变量是“name”,但在 string_length 的实现中不再使用“name”,而是使用“s”。
#include <cs50.h>
#include <stdio.h>
int string_length(string s);
int main(void)
{
string name = get_string("Name: ");
int length = string_length(name);
printf("%i\n", length);
}
int string_length(string s)
{
int i = 0;
while (s[i] != '\0')
{
i++;
}
return i;
}
When you call a function, you pass it arguments (or possibly zero arguments).当您调用 function 时,您将其传递给 arguments(或可能是零参数)。 In
int length = string_length(name);
在
int length = string_length(name);
, the code string_length(name)
calls the function string_length
with the argument name
. ,代码
string_length(name)
使用参数name
调用string_length
。
Arguments are passed by value to the function. Arguments 按值传递给 function。 The function receives the value of the arguments.
function 接收 arguments 的值。
When a function starts executing, its parameters are assigned the values of the arguments (C 2018 6.5.2.2 4).当 function 开始执行时,其参数被分配为 arguments (C 2018 6.5.2.2 4) 的值。 In
int string_length(string s)
, the code string s
declares s
to be a parameter of type string
.在
int string_length(string s)
中,代码string s
s
为string
类型的参数。 When the function starts execution, the parameter s
is assigned the value of the corresponding argument, much as if s = name;
当 function 开始执行时,参数
s
被赋值为对应参数的值,就像s = name;
had been executed.已被处决。
Then, inside the function, s
refers to this parameter, which has the value of the argument the function was called with.然后,在 function 内部,
s
指的是这个参数,它具有调用 function 的参数的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.