C Source Code/Functions

< C Source Code

This page is about computer programming functions. For mathematical functions, see Functions (mathematics).

This example is on functions. With Functions you need to state the return type of the function. Either int or void. Int is value used for returning something to a call, mainly used for returning integers such as the add function in the following program. Void is used for functions that don't return a value or you don't want to return a value. You must use int or void in every function you make. Take a look at the following program:

#include <stdio.h>
 
void cfile(char *file)
{
     FILE *fp = fopen(file, "w");
     fprintf(fp, "some text");
     fclose(fp);
}
 
int add(int x, int y)
{
     int r;
     r = x + y;
     return(r);
}
 
int main()
{
     cfile("example.txt");
     add(1,1);
     return 0;
}

You could have done this(it really doesn't make a difference):

#include <stdio.h> //standard C header
 
int cfile(char *file)
{
     FILE *fp = fopen(file, "w");
     fprintf(fp, "example");
     fclose(fp);
     return 0;
}
 
int add(int x, int y) //this must be int it's returning something to a function call
{
     int r;
     r = x + y;
     return(r);
}
 
int main()
{
     cfile("example.txt");
     add(1,1);
     return 0;
}

See also

This article is issued from Wikiversity - version of the Sunday, January 05, 2014. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.