Home > Blockchain >  What is the purpose of returning 1 or 0 from a function?
What is the purpose of returning 1 or 0 from a function?

Time:12-03

int SeqList<ElemType>::InsertElem(const ElemType &e)//insert at the taild
{
    if(length==maxLength)
        return 0;
    else
    {
        elems[length]=e;
        length  ;
        return 1;
    }
}

The purpose of this program is to implement a sequential list,and I want know the difference between return 1 and return 0 and the effect of them. Additionally, why not use void type?

CodePudding user response:

In the code you have provided, the return statements are used to indicate the success or failure of the InsertElem() function. The function is designed to insert a new element into a sequential list, but it will only do so if there is enough space in the list to accommodate the new element. If the list is full, the function will return 0 to indicate that the operation has failed. Otherwise, the function will insert the new element, increment the length of the list, and return 1 to indicate that the operation has succeeded.

The use of return statements in this way is a common pattern in programming, as it allows the calling code to determine whether an operation has succeeded or failed. In this case, the calling code can check the return value of the InsertElem() function and take appropriate action based on the result.

As for why the InsertElem() function doesn't use the void type, it is because the function is expected to return a value indicating the success or failure of the operation. The void type is used to indicate that a function does not return a value, so it would not be appropriate to use it in this case. Instead, the function uses the int type to indicate that it will return an integer value.

  • Related