When you define a function, you create a
signature for it: the parameters it needs to be given in order to work, and the type of the value it returns to your code.
In your first code snippet,
test_function
is declared as have a signature of accepting a single integer parameter, and returning an integer value.
So when you call it, you correctly provide one parameter, and use the result:
z = test_function(x);
You pass the value of x (not the variable itself - C always passes values rather than references, but don't worry about that for a moment) and return it multiplied by itself and two.
So you can supply the value ten, and it will return 200.
Your second version redefines
test_function
with a different signature: it now expects two integers to be passed to it, and still returns a single integer value.
But when you try to call the function:
z = test_function(x);
You only supply one parameter, so the system does not know what to do, and generates an error.
If you want to use that signature, you need to pass two parameters:
z = test_function(x, y);
But even then, your code as shown won't work:
int test_function(int x, int y)
{
int y = x;
x = 2 * y;
return (x * y);
}
Becuase the definition of a new
y
inside the body of the function "hides" the version you told it to expect as a parameter, and it isn't really sure which one you meant to use.
Try this:
int test_function(int x, int y)
{
int y2 = x;
x = 2 * y;
return (x * y2);
}
And
z = test_function(x, y);
and it should compile correctly.
Do note that the name of variables in one function have no bearing on those in another: you could write your function as this:
int test_function(int a, int b)
{
int c = a;
a = 2 * b;
return (a * c);
}
And it work exactly the same, because the names "x" and "y" are not transferred when you call the function, just the values they contained. Variables cannot be accessed directly outside the function in which they are declared unless they are used to pass a value to another function, or returned to the caller.