You are here:About>Computing & Technology>C / C++ / C#
About.comC / C++ / C#
Elsewhere on the Web

C Tutorial - Lesson Six - About Functions

From David Bolton,
Your Guide to C / C++ / C#.
FREE Newsletter. Sign Up Now!

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. Learn About Functions
  2. Calling a Function and Writing Your Own Functions
  3. Function Parameters
  4. Learn about Function Prototypes
  5. Learn more about how to write and use variadic functions.
  6. Learn how the variadic function total works

<< Previous | Next >>

Elsewhere on the Web

 All Topics | Email Article | Print this Page | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.