+ 1

Return statement

Guys i need help, i searched all over the Internet for examples and answers but couldn’t understand. when the method is void and i make an equation like for example 2 + 2 it will return the value 4 even tho its void. Then why should i use the return statement it doesn’t make any difference I am new to this i hope someone can help me understand why we use return and when

2nd Dec 2019, 4:19 PM
Hisham Ashraf
Hisham Ashraf - avatar
5 Answers
+ 3
void fun(int a, int b){ int ans = a + b; return ans; // error because return_type is void } You are mistaken with your example, you said that in function of return_type void you are getting as return value(2+2 = 4). However, its possible to display to value(2+2 = 4) by printing it on that very function. But if you want to get some result or want the changes in any of your variables then you use REFERENCE in C# using ref keyword. Please refer some source for learning ref if you dont know. Conclusion, if function is started with void then no values will be return and vice versa.
2nd Dec 2019, 4:48 PM
RKK
RKK - avatar
+ 2
Sometimes it's used just to exit the method and return control to another branch, but other than that it's useless in a void method.
2nd Dec 2019, 4:38 PM
Inkosi
Inkosi - avatar
+ 2
When a function returns a value, that value can be assigned to a variable. However this is not the case with void methods
4th Dec 2019, 12:53 PM
🇲​🇴​🇭​🇦​🇲​🇲​🇦​🇩​ 🇯​🇮​🇱​🇦​🇳​
🇲​🇴​🇭​🇦​🇲​🇲​🇦​🇩​ 🇯​🇮​🇱​🇦​🇳​ - avatar
+ 1
void means that does not return anything to calling method. Can you specify example Where you confused ? In the above example ,that is calculation happend in function. And that value, not return to calling method and not available outside of that function unless if you use global variables... Ex: int main() { Int a=2; change(a); cout<<a; return 0; } void change(int a) { a=7; cout<<a; // return; here will be error. } Here you get output: 7 2 change function does not return anything to main . just perform it action and goes back to next line of called statement.... edit : i showed in c++, but same in all languages about void. i think. is not it?
2nd Dec 2019, 4:41 PM
Jayakrishna 🇮🇳
+ 1
There is a difference between printing the value and returning the value. You can call a method which can return you something or else you can call a method which can print something for you but does not return anything. Void type does not return anything and is just used for printing the necessary data.
2nd Dec 2019, 4:42 PM
Avinesh
Avinesh - avatar