Home > Software engineering >  Why do I need a return in a do while loop?
Why do I need a return in a do while loop?

Time:11-30

This was related to this code from a CS50x (Week 2) class.

The code was:

int get_negative_int(void)
{
    int n;
    do
    {
        n = get_int("Negative integer: ");
        printf("n is %i\n", n);
    }
    while (n < 0);
    return n;
}

I was confused why the "return n;" line is needed. Wouldn't the do while loop keep running while n < 0 and once n > 0 shouldn't it stop and pass the > 0 value of n to the int n without the "return n;" line?

I didn't have any errors but I was having trouble understanding how return works in this instance. I feel I'm missing something basic about how return works here and any pointers would be appreciated!

CodePudding user response:

the only way to return a value from a function is via the return statement.

The do/while condition just controls the loop. Execution then continues at the next line.

CodePudding user response:

The return has nothing to do with the loop. Any function returning a value such as int get_negative_int(void) returning an int, needs to have a return statement, simple as that.

The CS50 task is to figure out what's wrong with the function. Hint: it ain't the return.

once n > 0 shouldn't it stop

Please note that the opposite of n < 0 is n >= 0. The loop will indeed stop while a number 0 or larger is entered.

  • Related