Want a deep explanation about calling methods | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Want a deep explanation about calling methods

24th Jul 2017, 5:13 PM
Vishesh Malhotra
Vishesh Malhotra - avatar
7 Answers
+ 1
What language?
24th Jul 2017, 5:25 PM
Mayank
Mayank - avatar
+ 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.
24th Jul 2017, 5:37 PM
Mayank
Mayank - avatar
0
C
24th Jul 2017, 5:25 PM
Vishesh Malhotra
Vishesh Malhotra - avatar
0
90 percent but an example can get it to 100
24th Jul 2017, 5:43 PM
Vishesh Malhotra
Vishesh Malhotra - avatar
0
more discussion on first point
24th Jul 2017, 5:48 PM
Vishesh Malhotra
Vishesh Malhotra - avatar
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.
24th Jul 2017, 5:53 PM
Mayank
Mayank - avatar
0
Anything else?
24th Jul 2017, 6:01 PM
Mayank
Mayank - avatar