Functions - parameters or arguments and return types

Most languages allow you to create functions of some sort. Functions are used to break up large programs into named sections. You have already been using a function which is the main function. Functions are often used when the same piece of code has to run multiple times.
In this case you can put this piece of code in a function and give that function a name. When the piece of code is required you just have to call the function by its name. (So you only have to type the piece of code once).
In the example below we declare a function with the name MyPrint. The only thing that this function does is to print the sentence: Printing from a function. If we want to use the function we just have to call MyPrint() and the printf statement will be executed. (Don’t forget to put the round brackets behind the function name when you call it or declare it).
Take a look at the example:

 #include<stdio.h>

 void MyPrint()
 {
  printf("Printing from a function.\n");
 }

 int main()
 {
  MyPrint();
  return 0;
 }

Parameters and return

Functions can accept parameters and can return a result. (C functions can accept an unlimited number of parameters).
Where the functions are declared in your program does not matter, as long as a functions name is known to the compiler before it is called. In other words: when there are two functions, i.e. functions A and B, and B must call A, than A has to be declared in front of B.
Let’s take a look at an example where a result is returned:

 #include<stdio.h>

 int Add(int output1,int output2 )
 {
  printf("%d", output1);
  printf("%d", output2);
  return output1 + output2;
 }

 int main()
 {
  int answer, input1, input2;

  scanf("%d", &input1);
  scanf("%d", &input2);

  answer = Add(input1,input2);

  printf(" answer = %d\n", answer);
  return 0;
 }

The main() function starts with the declaration of three integers. Then the user can input two whole numbers. These numbers are used as input of function Add(). Input1 is stored in output1 and input2 is stored in output2. The function Add() prints the two numbers onto the screen and will return the result of output1 + output2. The return value is stored in the integer answer. The number stored in answer is then printed onto the screen.

Void

If you don’t want to return a result from a function, you can use void return type instead of the int.
So let’s take a look at an example of a function that will not return an integer:


 void our_site()
 {
  printf("www");
  printf(".NextDawn");
  printf(".nl");
 }

Note: As you can see there is not an int before our_site() and there is not a return 0; in the function.
The function can be called by the following statement: our_site();

Previous Page                                                        Next Page

Spread the word! By sharing this Post!

Pageviews This Week