Saturday, May 22, 2010

Parameter passing without return values in C?

I need to make a program that doesn't return any values, so I can only use Pass by value or pass by reference (pointers)between the functions.





I can get my program to compile, but it doesn't give the right results, and I think I'm doing something wrong. I suspect it has to do with my parameter passing.





I have an input function, a calculation function, a print function, and the normal main function. Since I cannot return any values I'm not sure how to get the data from the input function into my calculation function, without returning values. All of my functions are called from main.





My program is something like this (briefly):





void getNumbers


/* get input of x and y with printfs, scanfs */





void getMod


/* a calculation involving x and y to get mod */





void printMod


/* printing the mod value*/





int main


getNumbers();


getMod(x, y);


printMod(mod);





I think I am getting confused about how to pass parameters. Could someone please help me out

Parameter passing without return values in C?
Something like this





void getNumbers (int* x, int* y)


{


/* do whatever gets numbers .... */





*x = 0; /* replace 0 with the number


*y = 0;


}





void getMod (int *mod, int y, int x)


{


*mod = x % y; /* replace with actual calculation */


}





int main ()


{


int x, y, mod;


getNumbers (%26amp;x, %26amp;y);


getMod (%26amp;mod, x, y);


printMod (mod);


}





Basically by putting the ampersand %26amp; in front of a variable you take its address. When you use that variable in a function put an asterisk * in front of the variable to mean its value.





In C++ you would do it a little different





void getNumbers (int%26amp; x, int%26amp; y)


{


/* do whatever gets numbers .... */





x = 0; /* replace 0 with the number


y = 0;


}





void getMod (int %26amp;mod, int y, int x)


{


mod = x % y; /* replace with actual calculation */


}





int main ()


{


int x, y, mod;


getNumbers (x, y);


getMod (mod, x, y);


printMod (mod);


}





Hope that helps
Reply:decide how you are planning to pass it


by value ? or by address (reference )


you can use pointers *var to pass by reference,


int *a for pointer variable


so use


void getMod( int *a, int *b)


{


// make calculation now.





}





or else just pass values


void getMod( int a, int b)


{


}





Note, you have to define variable out of function to keep it in memory ( remember variable defined within function life cycle is within its existance)





Done ?





Good luck
Reply:In your main pass in place holder variables to getnumbers to be pointers to the values, then use those to pass the pointers into get mod. Be sure to pass the paramebers by reference and to getNumbers and getMod. Print mod pass by value as you are not changing the data.





int main


getNumbers(x,y);


getMod(x, y);


printMod(x,y);

imperial

No comments:

Post a Comment