Sunday, November 10
Functions Continued (Functions Input)
Input in functions : type of input
We can use functions by 2 methods of input:
- input as passing arguments by values [Part 1;]
- input as passing arguments by reference [Part 2;]
Part 1; using function : passing arguments by value
Problem 1; scope of variable and functionality
- In this type, we give function the value of a variable not that variable...!!!
- Function creates a local scope variable (local to the functions body only)
- It does not change the value of original variable.
- Say we ran an square function which takes argument by value and argument is x
- When function is called it reserves memory of ram and makes a copy of value of x and runs operations on this copy
- In the end when it returns value then function is removed from memory so is that copy of variable
- Original variable remains intact
- This is how scope of variable is defined
Problem 2; returning complex values
Say we have to make a function which takes 5 variables and returns separate value
How to return this: compare those variables for largest one? Obviously we can't return this:
return if (num1>num2&&num1>num3){num1}; and if we have to put all five variables confirmation statements?
Here is a tip: make a local scope variable which will collect all those values which has to be returned in the end i.e.
_________________________________________________________________________________
int result; //this variable only exists while function is working when it is done this variable
will be removed so it is a local variable to this function only / must not match existing one
if (num1>num2&&num1>num3){result=num1;}
if (num2>num3){result=num2;}
else {result=num3;}
return result;
_______________________________________________________________________
Very easy!
Now every time you can just create your required variable and save returning values in it and return it easily....!!!!
==================================================================================================================================================
Till next time.. Please let me know your problem with syntax or logic or error so i can make better understanding in the article...!!!
Do comment in section below :)
Do comment in section below :)
0 comments :
Post a Comment