Search code examples
functionreturn

Can I use return 1, return 2 or any other integer instead of return 0 in a function if it is not returning an integer for a particular case?


here is my function:

int repeatedNTimes(int* A, int ASize)
{
    int i, count, j, temp;

    for(i = 0; i < ASize; ++i)
    {
        count = 0;
        temp = A[i];

        for(j = i; j < ASize; ++j)
        {
            if(A[i] == A[j])
                count++;
        }

        if(count == ASize / 2)
            return A[i];

        else
            continue;   
    }

    return 0;
}

Can I use return 1, or return (any integer) instead of return 0? And secondly, what if I don't return an integer?


Solution

  • If you do not return an integer, then the behavior is not well defined (probably undefined, but I don't have the standard memorized). Your compiler will likely emit a warning if you have warnings on.

    As for returning an integer other than 0, yes, you can do that. What matters is the return type of the function when it comes to what you can and cannot return. That said, returning a different result may not have the effect you want depending on what your function does. Sometimes values like zero are reserved for special conditions like not found.