Sunday, July 12, 2009

C Programming??

How to you take a value in a interger function [int function_name();] and use it back in the main part of your code??





Thanks.

C Programming??
It isn't entirely clear what you are asking, but there are a few ways that a function could perform some operation on an integer (or resulting in an integer) and have the caller see it.





The first would be as a return value. So if you had a function like this





int getHalf( int x ) {


return x / 2;


}





the caller could then have:





int halfValue = getHalf( 668 );





You can also pass variables by reference in C by passing in a pointer to them. That would look like this:





void makeHalf( int *x ) {


*x = *x / 2;


}





with the caller looking like





int x = 22;


makeHalf( %26amp;x );





Finally, you could have the function just access a global variable, but it is generally poor form to do so.





Hope this helps...
Reply:the most common way is by assigning the return value of the function in a variable.





int my_weight ()


{


return 195;


}





int x = 0; // initialize x to 0





printf("%d\n", x); // prints "0" to console





x = my_weight(); // x now equals 195





printf("%d\n", x); // prints "195" to console





int y = x/2; //use value in a calculation


// etc.
Reply:First ur function's to be written as follows:


int function_name()


{


.......


}








so as a result u've defined that it'll return an integer value.


another imp thing is that in the main part of ur code where u've called ur function, u've to tc that it's written as follows:





t = function_name();





where t is an integer that u've declared in any part of ur main code b4 the calling statement. after writing the previous statement, the integer variable t carries the integer value that's been returned frm ur function :) hope i've helped a lil.. for more help u're free to ask any questions :)


No comments:

Post a Comment