Passing data from the main argument into a function

Let me start with a sample code

#include <stdio.h>

Int add (int, int);

Void main()
    Int a, b, c;
    a = 20;
    b = 10;
    c = a + b;
    c = add (a, b);
    printf("Your answer is: %d", c);

Int add(int x, int y)
     Int z;
     z = x + y;
     return (z);

I am stuck at understanding how data are passed into this function: how variables from the main function are assigned to the parameters of a called function, then those data’s in the parameters getting assigned into the variables in the function itself

I will appreciate your help. Be it JavaScript or Python. I am just trying to get my understanding on the main logic of parameters, variables, argument and function. Not necessarily C

Small tweaks for conventions and correctness:

#include <stdio.h>

int add(int, int);

// this is the 'main' function 
// when you compile this code
// this is the part that runs
int main(void) { 
  // this says we will have 3 integers
  int a, b, c;

  // this sets the values of the first two
  a = 20;
  b = 10;

  // here we call the function add
  // using the values stored in a and b
  // c = a + b;
  c = add(a, b);
  printf("Your answer is: %d", c);

  return 0;

// this is the function add
// it runs whenever we call it
// with whatever values are passed in
int add(int x, int y) {
  // here we say we have one integer
  int z;
  // and set it to hold the sum of the arguments 
  z = x + y;

  return z;

Inside of main we call add with a = 20 and b = 10 so those are the values used in that function call.


This is really helpful. Let me brainstorm it and see how it works

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.