0

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 .

4

1 回答 1

3

A function that promises to return a value and does not induces Undefined Behavior (in C, only if the value is used).

Here your function has two executions paths:

int sum(int num) {
    if (sum > 0) 
        return num + sum(num - 1); // code path 1
    // code path 2
}

And in the second code path, it does not return anything.

Undefined behavior means anything can happen. The popular image is that daemons could start flying out of your nose. In practice, you are more likely to get a more or less random value depending on the implementation. Looks like in your case, for your compiler, this program and that set of optimizations (and maybe because the stars aligned, too) you get num. Lucky you.

By the way, my compiler gives a warning:

source.cpp: In function 'int sum(int)':
source.cpp:22:1: warning: control reaches end of non-void function [-Wreturn-type]
于 2012-11-10T16:19:55.267 回答