Below is the code :
The Code :
#include <iostream>
using namespace std;
int sum(int ); //To sum up the user input up to 1 , for e.g 4 = 4 + 3 + 2 + 1 = 10
int main(void)
{
int num;
int total;
cin >> num;
total = sum(num);
cout << total;
return 0;
}
int sum(int num)
{
if(num > 0) // How if num is -1 or -10??
return num + sum(num - 1);
}
The Question :
1.) I try to execute the above code and input value that violate the if condition for e.g -1
or -100
. But still when I cout
the total
variable I get back the value I've given to the variable num
.
2.) My question is , is this a standard behavior ? Because I can run this code without getting any warning or error saying there's no return
statement stated I don't have an extra return
statement in case the num is violating the condition . So is this returning- the-original-value-if-the-condition-is-not-true something normal or it depends on the compiler being used ?
THank you .