Why do we need to return a value from a function??? Does that value can be useful if returned??In which sense???? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why do we need to return a value from a function??? Does that value can be useful if returned??In which sense????

4th Nov 2016, 2:13 PM
sadia sharif
3 Answers
+ 6
function returning value itself act like the returned value. for example we do int a=3; here value of a is 3; now for. int b= a here value of b is 3; similarly if we write this int twice(x){ int y; y= 2*x; return y; } int a=twice(b); then a is 6 and the function acts like the returned value. also this return specifies all the variables to be used as returning output from. and the data types of returning variable and the function should be same. In some function we write commands to be run and nothing to be returned hence there is no need of return command
4th Nov 2016, 3:51 PM
Sandeep Chatterjee
+ 4
You do not necessarily need a return value. You can create functions to do large/small tasks without returning anything Example: void myFunc() { cout << "I am a void function." << endl; cout << "I won't return anything." << endl; } If you give your function a data type then you're basically asking for a value to be returned so it can be used in your main function. Example: bool isABigger(int a, int b) { if (a > b) { return true; } else { return false; } } int main() { int a = 2; int b = 3; myFunc(); if (isABigger(a, b)) { cout << "True" << endl; } else { cout << "False" << endl; } return 0; } Hope this helps.
4th Nov 2016, 2:31 PM
Jose Ramirez
Jose Ramirez - avatar
+ 2
thanks Jose C.Ramirez that was really helpful...
4th Nov 2016, 2:34 PM
sadia sharif