adding variables together in a function
Author Message
adding variables together in a function

Have a program I am writing that calculates grades. Two functions are called
that generate a final total for each one, my problem is when a third
function is called I add these two totals

EX: total=p3 + e3

my total value comes out as 0 rather than the total of p3 and e3. Do I need
to store these values generated earlier so they remember it when getting the
combined total value in the third function?

many thanks,
Dave....

Sat, 21 Apr 2001 03:00:00 GMT
adding variables together in a function
--
Hypertext C-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-FAQ ftp: ftp://rtfm.mit.edu, C-FAQ Book: ISBN 0-201-84519-9
Try "C Programming: A Modern Approach" ISBN 0-393-96945-2
Want Software?  Algorithms?  Pubs? http://www.infoseek.com

Sat, 21 Apr 2001 03:00:00 GMT
adding variables together in a function

Quote:

> Have a program I am writing that calculates grades. Two functions are called
> that generate a final total for each one, my problem is when a third
> function is called I add these two totals

> EX: total=p3 + e3

> my total value comes out as 0 rather than the total of p3 and e3. Do I need
> to store these values generated earlier so they remember it when getting the
> combined total value in the third function?

Hi Dave,

could be any number of different reasons. For instance what should
work is:
int get_total( int p3, int e3 )
{
return p3 + e3;
}

Or if you want to use a local variable "total":
int get_total( int p3, int e3 )
{
int total;
total = p3 + e3;
}

But what will not work is:
void get_total( int p3, int e3, int total )
{
total = p3 + e3;
}
(because in C parameters are passed by value, ie. "total" is a copy
of the value passed in by the caller)

To make this work, you should change it to:
void get_total( int p3, int e3, int *pTotal )
{
*pTotal = p3 + e3;
}

And it is called like this:

int main( void )
{
int total;
get_total( 42, 24, &total );
return 0;
}

Instead of giving the value of "total" to the function, you tell the
function where "total" is located. And inside the function you can
use that location to change the value that is located there.

Stephan
(initiator of the campaign against grumpiness in c.l.c)

Sun, 22 Apr 2001 03:00:00 GMT

 Page 1 of 1 [ 3 post ]

Relevant Pages