+ 1
Want a deep explanation about calling methods
7 ответов
+ 1
What language?
+ 1
A function is a module which does something specific that you use quite often and helps us remove code duplicacy. In C when you call a function, the function gets a separate memory from your stack space for storing its variable (which is freed as soon as the function has finished its job). So its obvious you cant use a variable from some other function as each has its own stack space.
Now there are two means by which you can send data to the function you are calling.
1. Call by value: The data you send as argument for the function is copied and whatever you do in that function is not reflected back to the main function. The main function only gets back the returned value.
int sum(int a, int b)
{
a = a+b; // changing value of a doesn't affect x in main function
return a;
}
void main()
{
int x=5,y=10;
int z=sum(x,y);
cout<<z;
}
2. Call by reference: You send the memory address of your data as argument to the function. The function gets a pointer to that memory address, you can ask the compiler to change the value or get the value at this memory address. Now note that this memory address belongs to the calling function (main), so when you change the value at this address your main function variable is also getting changed.
Example :
int sum(int &a, int &b) // call by reference
{
a=a+b; // changing a changes x in main
return a;
}
void main()
{
int x=5,y=10;
int z= sum(x,y);
cout<<z;
}
Let me know if you want to discuss more.
0
C
0
90 percent but an example can get it to 100
0
more discussion on first point
0
Can you please be more specific?
My first point was about code duplicacy.
Suppose you want to swap variables.
void swap(int &a,int &b)
{
int temp= a;
a=b;
b=temp;
}
So here you can see declaring a separate function helps if you want to swap two variables more than once.
Instead of writing this swap code more than once in your main function you can just use this swap function.
Note: Swap function is passed by reference so that swapping reflects in your main function.
0
Anything else?