I have:
#include <stdio.h>
int sum ( int x, int y );
main ()
{
int theSum = sum (10, 11);
printf ( "Sum of %i and %i is: %i\n", x, y, theSum );
}
int sum ( int x, int y )
{
return x + y;
}
However, when I compile and run it says x and y are undeclared? Any help greatly appreciated. Thanks
In line three all you have done is declare a function sum
which takes two parameters, both integers, called x
and y
. You haven't declared any variables. Those parameters can only be referred to inside the function itself. Below is a simplification which will help you at this stage, but you should try to read a basic programming book. "The C Programming Language" by Kernighan and Ritchie is a fine place to start.
Variables are chunks of memory that you refer to by name. They can take on any value (of their type) during the life of your program - hence the name 'variable'. They must be declared before you use them; you do this by telling the compiler their type and their name. int a
means 'reserve me a block of memory big enough to hold any integer, and let me refer to it later with the name a
'. You can assign values to it: a = 10
and you can make use of it: a + 20
.
You need to understand the difference between parameters and variables to get what's going on here. A function's parameters are basically variables which exist only during the life of that function. Here's your sum
again:
int sum(int x, int y) {
return x + y;
}
Notice how the top line looks just like a variable declaration int x
. That's because it is. x
and y
are variables you can use in the function.
You call sum
by passing in values. The compiler, in effect, replaces x
and y
in your function with the values you pass in. In your case, you're passing literals: 10 and 11. When the program reaches the call to sum
, the parameters x
and y
take on the values 10 and 11, so the return becomes return 10 + 11;
which is of course 21.
Just remember that the parameters x
and y
only exist in that function. You may only refer to them within your function. Why? Because each pair of curly braces {
and }
define a scope, and anything declared within that scope can only be used within that scope. That includes variables and parameters.
So, here is a more complete example. I have changed the letters so you can see the different ways you use variables and parameters:
#include <stdio.h>
int sum ( int x, int y );
main ()
{
/* We declare our variables */
int a;
int b;
/* We assign values to them */
a = 10;
b = 11;
/* We pass them as parameters to your sum function */
int theSum = sum (a, b);
/* And we use them as parameters again, in a call to the printf function */
printf ( "Sum of %i and %i is: %i\n", a, b, theSum );
}
int sum ( int x, int y )
{
return x + y;
}