[Solved] C++ beginner got 42 [closed]


The function bool lessThanOrEqualToZero(int);, as defined, makes your program have undefined behavior since not all paths in the function leads to the function returning a bool that you declared that it should return. Specifically: If num > 0 is true the function doesn’t return a value.

When a program has undefined behavior, you can’t trust anything it does. Your program could therefore print just about anything or nothing, crash or do something completely wild.

In some compilator implementations, a value could be picked from the stack where it expects to find the promised bool and then print whatever that value was (42 in your case). The stack will then be corrupt. Other implementations may compile it into a program that does something completely different. You’ll never know.

The solution is to make sure that all paths leads to a return:

bool lessThanOrEqualToZero(int num)
{
    if (num <= 0) {
        return true;
    }
    return false;
}

This however better written as:

bool lessThanOrEqualToZero(int num)
{
    return num <= 0;
}

0

solved C++ beginner got 42 [closed]