1. Technology

C Tutorial - Lesson Six - About Functions

By

2 of 6

Calling a Function and Writing Your Own Functions
In this example we'll call the function pow() in <math.h>. It calculates xy where both x and y are doubles and x is positive. Create a project called ex6_1 or load the sample project ex6_1.
 #include <math.h> 
 #include<stdio.h>
 int main() {
 double x=5.7;
 double y=3;
 double answer= pow(x,y) ;
 printf("The result of %f to the power of %f is %f",x,y,answer) ;
 return 0;
 }
 This outputs : The result of 5.700000 to the power of 3.000000 is 185.193000 

Writing Functions

Functions divide a program into smaller manageable chunks. It's usual to group related functions into libraries and then use a header file to make public those functions. That way, other parts of your application can call them.

Return Type

All functions have a return type. If you omit it, then int is assumed. So you should always specify the return type.

A function can return nothing- just like a procedure in pascal. In C this is done with the void type. E.g.

 void StartLogging() {
 // Logging Code
 }
 

Return Value

Other than in a void function, a value of the function's return type must be returned. This is done with the return statement. This also exits the function. For a void function, return by itself will do.
 //ex6_11
 #include <stdio.h>
 int addtwonumbers(int a,int b) {
 return a + b;
 }
 
 int main() {
 int c = addtwonumbers(6,7) ;
 printf("C= %i ",c) ;
 return 0;
 }
 
This adds two numbers and outputs C= 13.

On the next page : Learn about function parameters.

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C Programming
  5. C Tutorials
  6. Calling a Function and Writing Your Own Functions

©2014 About.com. All rights reserved.