20 likes | 135 Views
Passing By Reference. March 8, 2005 first given, no handouts, work done in class. #include <stdio.h> #include <stdlib.h> /* Name: Passing variables by reference Author: B. Smith Date: 08/03/06 11:18 Description: Based on textbook problems on p259, 5a and 5b.
E N D
Passing By Reference March 8, 2005 first given, no handouts, work done in class
#include <stdio.h> #include <stdlib.h> /* Name: Passing variables by reference Author: B. Smith Date: 08/03/06 11:18 Description: Based on textbook problems on p259, 5a and 5b. sec() does a simple calculation to get total number of seconds . sec2() does same calculation, but receives and modifies a reference to a variable. */ int sec(int, int, int ); //calculates and returns total number of seconds void sec2(int, int, int, int* ); //calculates total num of seconds and stores in a received address int main() { int totSecs; // total number of seconds int h,m,s; // hours, minutes, seconds h = 1; //1 hour = 3600 seconds m = 2; //2 minutes = 120 seconds s = 5; //5 seconds = 5 seconds //TOTAL: = 3725 SECONDS printf("Total number of seconds is %d \n", sec(h,m,s) ); sec2( h, m, s,&totSecs ); printf("Total number of seconds using pass-by-reference is %d \n", totSecs ); system("pause"); return EXIT_SUCCESS; } /*--------------------------------------------------------------------------*/ // Simple function to calculate total number of seconds // (eg 1h, 2 min, 5 sec = 3725 seconds) /*--------------------------------------------------------------------------*/ int sec(int hr, int mi, int se) { int total = hr*3600+mi*60+se; return total; } /*--------------------------------------------------------------------------*/ // No values are returned directly, but this functin returns values by modifying // the variable referred to by int* totPointer. totPointer is a pointer to the // the value we wish to modify. /*--------------------------------------------------------------------------*/ void sec2(int hr, int mi, int se, int* totPointer) { *totPointer = hr*3600+mi*60+se; }