1

im doing the CS50. They discuss functions.

  #include <cs50.h>
  #include <stdio.h>

  const int array_length = 3;

  float average(int length, int array[]);

  int main(void)
  {
      int scores[array_length];
      for (int i = 0; i < array_length; i++)
      {
          scores[i] = get_int("Score: ");
      }

      printf("Average: %f\n", average(array_length, scores));
  }

  float average(int length, int array[])
  {
      int sum = 0;
      for (int i = 0; i < length; i++)
      {
          sum += array[i];
      }
      return sum / (float) length;
  }

In the function they declaring the "length" variable. But why they do not assign a value to it? How C knows the "length" is 3 ?

  • 1
    The function *call* `average(array_length, scores)` assigns the value `array_length` to the argument `length`. – Weather Vane May 30 '21 at 19:01
  • @Peter_Elfen22 The compiler knows that the size of the array equal to 3 due to this declaration const int array_length = 3; – Vlad from Moscow May 30 '21 at 19:04
  • @Yunnosch I will think about this tomorrow. – Vlad from Moscow May 30 '21 at 19:14
  • @VladfromMoscow Too late. ;-) – Yunnosch May 30 '21 at 19:19
  • I challenge the proposed duplicate. Discussing the general problem of finding the length of an array (especially inside a function and problematically with only the array as parameter) is not applicable in this case, where the shown code has an interesting (and in appropriate use cases more efficient) solution which OP just asks about for the purpose of understanding. The existing answer here is much better for the question as asked. @0___________ – Yunnosch May 30 '21 at 19:22

1 Answers1

1

When you call the average() function from main you are passing the two values also, like average(array_length, scores). Then, as declared by the prototype float average(int length, int array[])the function catches those values.

array_length --> length

scores --> array[]

And look that the length is globally declared here - const int array_length = 3;. So, the parameter length got the value of array_length also.

You can say, array_length = 3 = length.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Please mention that using the constant in `int scores[array_length];` guarantess that the value of `array_length` is reliably the actual length of the array. That would nicely round your answer off to become upvotable in my opinion. – Yunnosch May 30 '21 at 19:17
  • Good explanation. But why I can not use this variable inside the function array_length --> array_length scores --> scores [] – Peter_Elfen22 May 31 '21 at 18:50