C - Constructing a function

Introduction

All functions have a name, which must be unique; no two functions can have the same name.

A function cannot have the same name as a keyword.

The name is followed by parentheses, which are then followed by a set of curly brackets.

So at its simplest construction, a function looks like this:

type functionName() { } 

type defines the value returned by a function.

Options for type include all the standard C variable types - char, int, float, double - and void for functions that don't return anything.

Functions that return a value must use the return keyword.

The return statement either ends the function or passes a value back to the statement that called the function.

For example:

return; 

The following statement passes the value of the something variable back to the statement that called the function.

The something must be of the same variable type as the function, an int, the float, and so on.

return(something); 

Functions that don't return values are declared of the void type.

Those functions end with the last statement held in the curly brackets; a return statement isn't required.

Functions must be prototyped in your code.

The prototype describes the value returned and any values sent to the function.

The prototype can appear as a statement at the top of your source code.

The following code defines a basic function with no return.

Demo

#include <stdio.h> 

void prompt();      /* function prototype */ 

int main() // ww w.  ja  va  2 s  .c o  m
{ 
   int loop; 
   char input[32]; 

   loop=0; 
   while(loop<5) 
   { 
       prompt(); 
       fgets(input,31,stdin); 
       loop=loop+1; 
   } 
   return(0); 
} 
void prompt() { 
   printf("C:\\DOS> "); 
}

Result

Related Topic