#include <iostream>
usingnamespace std;
int function1()
{
int x = 12;
cout << x << endl;
}
int main()
{
int y = 3;
cout << y << endl;
return 0;
}
when i ran it, it would compile but i would get a warning saying "Line 8: control reaches end of non-void function "
but if i did this it would compile without warnings:
1 2 3 4 5 6
int function1()
{
int x = 12;
cout << x << endl;
return x;
}
i know that void functions do not have a return type. but i also thought that even though i declared my function an int, i thought that returning something was OPTIONAL. so why am i getting warnings. is there any way to get rid of the warnings with having to "return x;" ?
You are telling the compiler you are returning something, so why wouldn't you want to return anything? What would happen if your function that is supposed to return an int but doesn't is used as an int somewhere such as on the right side of an assignment operator?
one thing you have to keep in mind when using functions is the variable scope. You can't reference x in main because the free store gets rid of it when the function returns control back to main.
so whatever the return type is, is what you need to return. If you don't need to return anything then make it void.
in you above example, it was pointed out that x is deleted once that function reaches the end. What if we wanted to use that variable back in int main() ?we could do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int function1()
{
int x = 12;
cout << "x = " << x << endl; // x = 12
return x;
}
int main()
{
int y = 3;
cout << "y = " << y << endl; // y = 3
y = function1(); // here I assign the integer y to the function, which means its value becomes the returned value not the function.
cout << "Now y = " << y << endl; // y = 12
return 0;
}
Functions not declared to return void must return a value in all paths of execution that reach the end of the function.
The ONE EXCEPTION to this rule is main -- main needn't return anything even though it should be declared to return
int. This is ONLY because lazy C programmers often didn't return anything from main, and enforcing this rule in C++
would essentially break backwards compatibility with C. But the good programmer will return something from main,
even if always zero, because it takes about 2 seconds to type "return 0;" at the end of main.