Solution for Exercise 8-6

ex0806

#include <stdio.h>

#define SECRET 17

int main()
{
    int guess;

    printf("Can you guess the secret number: ");
    scanf("%d",&guess);
    if(guess==SECRET)
    {
        puts("You guessed it!");
        return(0);
    }
    if(guess!=SECRET)
    {
        puts("Wrong!");
        return(1);
    }
}

Notes

* Technically, the program doesn't need a final return statement. Both conditions evaluated are absolute, so one or the other is executed. The return belonging to either if statement is enough to end execution. A final return would be superfluous. Even so:

* The compiler warning you may see reflects the fact that main() is an int function and it requires a return statement near its bottom. That's an example of one of those warnings you can freely ignore — but only when you understand that in a program like this, logic shows that return isn't necessary.

* Generally speaking, you can stick a return anywhere in a function, well, anywhere that's logical. For example, an if evaluation could determine whether the function is done and use a return to end the function. But when the condition isn't met, the rest of the function runs. In that example, a final return would still be necessary — especially in the main() function to return a value to the operating system.