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
sumwhich takes two parameters, both integers, calledxandy. 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 ameans ‘reserve me a block of memory big enough to hold any integer, and let me refer to it later with the namea‘. You can assign values to it:a = 10and 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
sumagain:Notice how the top line looks just like a variable declaration
int x. That’s because it is.xandyare variables you can use in the function.You call
sumby passing in values. The compiler, in effect, replacesxandyin your function with the values you pass in. In your case, you’re passing literals: 10 and 11. When the program reaches the call tosum, the parametersxandytake on the values 10 and 11, so the return becomesreturn 10 + 11;which is of course 21.Just remember that the parameters
xandyonly 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: