Home > Back-end >  Why does this code work? The input for the function is "string s" but the actual input we
Why does this code work? The input for the function is "string s" but the actual input we

Time:08-02

SUMMARY OF THE CODE: This code is supposed to take a string input from the user and output how many characters there are. (Not using strlen intentionally)

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.

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.

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.

#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;
}

CodePudding user response:

When you call a function, you pass it arguments (or possibly zero arguments). In int length = string_length(name);, the code string_length(name) calls the function string_length with the argument name.

Arguments are passed by value to the function. The function receives the value of the arguments.

When a function starts executing, its parameters are assigned the values of the 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. When the function starts execution, the parameter s is assigned the value of the corresponding argument, much as if 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.

  • Related