1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Six - About Functions

By David Bolton, About.com

3 of 6

Function Parameters

Parameters are values passed into a function. Each parameter must have its type declared.

Tip : If you are using floats instead make them doubles as C will convert them anyway and give you warnings.

Here is an example EX6_2 with two parameters.

// ex6_2
#include "stdafx.h"
#include <stdio.h>

double getpercent(double a, double b ) {
return a/b*100.0;
}

int main () {
// Call the function
double value = getpercent(10.6,90.2) ;
printf("The percentage is %f",value) ;
return 0;
}
This is a simple function with two parameters a and b that are both doubles. It calculates the percentage of a to b and returns that value.

The output from this is

The percentage is 11.751663

Parameter Passing - Pass By Value

In C, pass by value is the mechanism used to pass parameters into a function. A copy is made of the variable and that copy is used. This is important. Not so much for int or double variables but larger data structures like arrays or structs.

Because a copy is used, the function cannot alter variables that are passed in. Parameters only pass values in, not out. This is called Pass by Value.

The alternative is Pass by Reference but you need C++ for that as C does not support this. There is a workaround in C but it needs pointers and in the next lesson, we'll cover those.

On the next page : Learn about Function Prototypes.

3 of 6

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2008 About.com, a part of The New York Times Company.

All rights reserved.